After spending lots of hours on Stackoverflow site, I have found some questions about control flow based on instance type. For example:

How can simplify that snippet? Is this the only way?

object obj = GetObject();
if (obj is MyClass)
{
  var casted = obj as MyClass;
  // actions
}

if (obj is OtherClass)
{
  var casted = obj as OtherClass;
  // actions
}

First of all - If you have such a situation - your design of architecture is bad. I’m almost sure that problem can be solved by changing structure of your classes.

I’m stubborn / I don’t want to change my class design / I just want to know the answer

Dynamic feature

You can use dynamic (introduced in C# 4.0):

void MyAction(MyClass class)
{
}

void MyAction(OtherClass)
{
}

object obj = GetObject();
MyAction((dynamic)obj);

How does it work? Dynamic forces to resolve type at runtime, so proper overload will be chosen. Main drawback? If you forget to prepare overload for type, you will get runtime binder-exception.

Generic invoker

To get benefit from dynamic and if approach I have prepared small library with Fluent API:

object obj = GetObject();
obj.DetermineType().When((MyClass target) => { /* action */ })
                   .When((OtherClass target) => { /* action */ })
                   .WhenMissing(_ => { /* action */ })
                   .Resolve();

c# 7.0 - possible solution

There is feature proposal for C# 7.0 called Declaration Expressions:

if (var myClass = obj as MyClass) 
{
    //use myClass here
}

It was planned feature for C# 6.0, but was finally cut-out.


Patryk Wąsiewicz

A very casual blog about programmer's life.