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;
}
Note that the “is” and “as” is duplicating the test; either use
isand then (once you know) just cast – or useasin the first place and test fornull.Re your issue; if you only want to do one thing – then cast:
Otherwise – perhaps a
virtualmethod (on the base-type), or just refactor the logic out into another method, so you have:But persoanlly, I’d just use the extra variable: