egrunin
egrunin

Reputation: 25083

Derived classes as return value

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?

Upvotes: 1

Views: 421

Answers (2)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59151

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.

public class SysState {
  /* nothing much here, except...: */
  public abstract virtual void DoSomething();
}

public class Normal : SysState {
  /* properties & methods */
  public override void DoSomething()
  {
    // ...
  }
}

public class Foobar : SysState {
  /* different properties & methods */
  public override void DoSomething()
  {
    // ...
  }
}

SysState result = SomeFunctionThatReturnsObjectDerivedFromSysState();

result.DoSomething();

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.

Upvotes: 1

ssube
ssube

Reputation: 48337

You might try combining handleX and placing Handle in SysState and over-riding it in both Normal and Foobar to perform specific tasks. It may not be the perfect solution, but it would look relatively neat. If you need to input data from other sources, pass them as parameters?

public class SysState
{
    public bool Process(Information info)
    {
        return ( info.Good );
    }
}

public class Normal
{
    public bool Process(Information info)
    {
        return doStuff();
    }
}

public class Foobar
{
    public bool Process(Information info)
    {
        return diePainfully();
    }
}

Obviously just an example, not knowing what HandleNormal and HandleFoobar do, but it could work nicely.

Upvotes: 0

Related Questions