How to treat an instance variable as an instance of another type in C#
- by Ben Aston
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;
}