Given these C# classes (generated by WCF, I can’t change these):
public SysState GetSysState();
public class SysState { /* nothing much here */}
public class Normal : SysState { /* properties & methods */ }
public class Foobar : SysState { /* different properties & methods */ }
My code (currently):
SysState result = GetSysState();
if (result is Normal) HandleNormal((Normal) result);
if (result is Foobar) HandleFoobar((Foobar) result);
My question: I keep feeling I’m missing something obvious, that I shouldn’t need to check type explicitly. Am I having a senior moment?
Use a virtual method. Put your code in the classes that they operate on, not in some code that gets a reference to the class.
This will execute the derived class’s DoSomething method. This is called polymorphism, and is the most natural (and some would argue the only correct) use of inheritance.
Please note that SysState.DoSomething doesn’t have to be abstract for this to work, but it does have to be virtual.