There's another thing to think about besides the way that the compiler handles switch
statements, and that's the functioning of the is
operator. There's a big difference between:
if (obj is Foo)
and
if (obj.GetType() == typeof(Foo))
Despite the name, the is
operator tells you if an object is compatible with a given type, not if it is of the given type. This leads to not-entirely-obvious bugs (though this one's pretty obvious) that look like:
if (obj is System.Object)
{
//this will always execute
}
else if (obj is Foo)
{
//this will never execute
}
Many of the suggestions here point you in the direction of using the object's type. That's fine if what you really want is logic associated with each type. But if that's the case, walk carefully when using the is
operator.
Also: though you can't modify these base types, that doesn't mean that you can't use Owen's suggestion. You could implement extension methods:
public enum MyType { Foo, Bar, Baz };
public static class MyTypeExtension
{
public static MyType GetMyType(this Foo o)
{
return MyType.Foo;
}
public static MyType GetMyType(this Bar o)
{
return MyType.Bar;
}
public static MyType GetMyType(this Baz o)
{
return MyType.Baz;
}
}
Then you can use a switch
statement:
switch (myObject.GetType())
{
case MyType.Foo:
// etc.