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());
}
}
Another way would be to define an interface IThing and then implement it in both classes here's the snipet:
You should really be overloading your method, not trying to do the disambiguation yourself. Most of the answers so far don't take future subclasses into account, which may lead to really terrible maintenance issues later on.
As Pablo suggests, interface approach is almost always the right thing to do to handle this. To really utilize switch, another alternative is to have a custom enum denoting your type in your classes.
This is kind of implemented in BCL too. One example is MemberInfo.MemberTypes, another is
GetTypeCode
for primitive types, like:This is an alternate answer that mixes contributions from JaredPar and VirtLink answers, with the following constraints:
Usage:
Code:
Create a superclass (S) and make A and B inherit from it. Then declare an abstract method on S that every subclass needs to implement.
Doing this the "foo" method can also change its signature to Foo(S o), making it type safe, and you don't need to throw that ugly exception.
With C# 7, which shipped with Visual Studio 2017 (Release 15.*), you are able to use Types in
case
statements (pattern matching):With C# 6, you can use a switch statement with the nameof() operator (thanks @Joey Adams):
With C# 5 and earlier, you could use a switch statement, but you'll have to use a magic string containing the type name... which is not particularly refactor friendly (thanks @nukefusion)