How to treat an instance variable as an instance of another type in C#

Posted by Ben Aston on Stack Overflow See other posts from Stack Overflow or by Ben Aston
Published on 2010-03-18T17:35:35Z Indexed on 2010/03/18 17:41 UTC
Read the original article Hit count: 404

Filed under:
|
|

I have a simple inheritance heirarchy with MyType2 inheriting from MyType1.

I have an instance of MyType1, arg, passed in as an argument to a method. If arg is an instance of MyType2, then I'd like to perform some logic, transforming the instance. My code looks something like the code below.

Having to create a new local variable b feels inelegant - is there a way of achieving the same behavior without the additional local variable?

public MyType1 MyMethod(MyType1 arg) 
{
    if(arg is MyType2)
    {
        MyType2 b = arg as MyType2;
        //use b (which modifies "arg" as "b" is a reference to it)...
    }

    return arg;
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about inheritance