C# – How to switch on type

Sometimes you may find it necessary to have conditional logic based on an object’s type. The simplest way to do this is to switch on the type, like this:

IPerson person = GetPerson();

switch (person)
{
	case Coder coder:
		coder.WriteCode();
		break;
	case TruckDriver truckDriver:
		truckDriver.PickUpCargo();
		truckDriver.DeliverCargo();
		break;
}
Code language: C# (cs)

This feature is called type pattern matching. Before this feature was added (in C# 7), you’d have to use a bunch of if-else’s and check the type like this: if (object.GetType() == typeof(Coder)). As you can see, type pattern matching with a switch is much simpler.

This is useful when you can’t use polymorphism and must explicitly check the object’s type. Note: This isn’t the same as the ‘switch statement’ code smell where you *can* use polymorphism.

Switching on an object

You can switch on an object variable and add switch cases for ANY type. Yes, even primitive types and strings. Here’s an example:

object person = GetPerson();

switch (person)
{
	case Coder coder:
		coder.WriteCode();
		break;
	case TruckDriver truckDriver:
		truckDriver.PickUpCargo();
		truckDriver.DeliverCargo();
		break;
	case string personString:
		Console.WriteLine(personString);
		break;
	case int personInt:
		Console.WriteLine(personInt);
		break;
}
Code language: C# (cs)

This is very useful when you’re dealing with an object that could be any type at all.

Can’t have switch cases with types that the object can’t possibly be

When you switch on a type, you can only have switch cases for types that the object could be. Otherwise, you get a compile-time error, like this:


Error CS8121 An expression of type ‘Coder’ cannot be handled by a pattern of type ‘TruckDriver’.

Here’s an example of code that produces this error. The person object is declared as type Coder. It can’t possibly be type TruckDriver, so that results in the CS8121 error:

Coder person = new Coder();

switch (person)
{
	case Coder coder:
		coder.WriteCode();
		break;
	case TruckDriver truckDriver:
		truckDriver.PickUpCargo();
		truckDriver.DeliverCargo();
		break;
}
Code language: C# (cs)

Think about what I mentioned before. When you switch on an object, you can put switch cases for ANY type. This is because an object could be any type. In general, it’s most useful to switch on interface/abstract base class/object types.

Leave a Comment