I need some help. It is pretty easy. I have this piece of code, and I would like to discuss if it is correct, or if you suggest a better way to do it. I have an idea about the a
There are some optimizations possible.
myObject is ClassA
, you don't need the soft cast. Instead you can do the cast directly: var myObjectA = (ClassA)myObject;
.((ClassA)myObject)?.MethodJustInA();
.myObject is ClassA
evaluates to false if myObject
is null, you don't need to do the check again: ((ClassA)myObject).MethodJustInA();
.So:
if (myObject is ClassA)
{
((ClassA)myObject).MethodJustInA();
}
else if (myObject is ClassB)
{
var myObjectB = (ClassB)myObject;
myObjectB.MethodJustInB();
myObjectB.OtherMethodJustInB();
}