Your only option is an equivalent to if-else-if structure. switch does not allow switch on type, because the switch structure needs an enumerable ensemble with mutually exclusive values (and an object can be of several types).
Edit for Abbas comment:
GetType().Name is valid but will lead you to potential errors in this context, because it can return a type you don't know. Even if an object is stored as a type A, GetType().Name can potentially return "B" if B inherits A. If you don't know B in the context of the method doing the switch (it could be a type from another library that inherits one of the current library, it could be a type that has been added after you wrote your method), you will miss it in your pseudo-typeswitch. If you write if(obj is A)
though, you won't.
Example, if I write this:
/// <summary>
/// Displays ":)" if obj is a Foo
/// </summary>
public static void CaseType(object obj)
{
switch(obj.GetType().Name)
{
case "Foo":
MessageBox.Show(":)");
break;
default:
MessageBox.Show(":(");
break;
}
}
The comment is a lie, because
public class Bar : Foo
{
}
public static void CaseTypeSpecialized()
{
Foo obj = new Bar();
CaseType(obj);
}
will display ":(".
It will work if you write
/// <summary>
/// Displays ":)" if obj is a Foo
/// </summary>
public static void CaseType(object obj)
{
if (obj is "Foo")
{
MessageBox.Show(":)");
}
else
{
MessageBox.Show(":(");
}
}
It's the concept of switch that is incompatible with non-mutually exclusive values. That's why you can get compilation errors when you switch on a Flags enum when the values are not exclusives.