Seeing as C# can't switch on a Type (which I gather wasn't added as a special case because is-a relationships mean that more than one distinct case might apply), is there a better way to simulate switching on type than this?
void Foo(object o)
{
if (o is A)
{
((A)o).Hop();
}
else if (o is B)
{
((B)o).Skip();
}
else
{
throw new ArgumentException("Unexpected type: " + o.GetType());
}
}
With JaredPar's answer in the back of my head, I wrote a variant of his
TypeSwitch
class that uses type inference for a nicer syntax:Note that the order of the
Case()
methods is important.Get the full and commented code for my
TypeSwitch
class. This is a working abbreviated version:One option is to have a dictionary from
Type
toAction
(or some other delegate). Look up the action based on the type, and then execute it. I've used this for factories before now.I looked at a few options here, mirroring what F# can do. F# has much better support for type-based switching (although I'm still sticking to C# ;-p). You might want to see here and here.
Yes thank to C#7 this can be achieved, here's how it's done (using expression pattern):
You can create overloaded methods:
And use dynamic parameter type to bypass static type checking:
If you were using C# 4, you could make use of the new dynamic functionality to achieve an interesting alternative. I'm not saying this is better, in fact it seems very likely that it would be slower, but it does have a certain elegance to it.
And the usage:
The reason this works is that a C# 4 dynamic method invocation has its overloads resolved at runtime rather than compile time. I wrote a little more about this idea quite recently. Again, I would just like to reiterate that this probably performs worse than all the other suggestions, I am offering it simply as a curiosity.