C# - Switch on Type

C# - Switch on Type

c#, switch, type

Prior to C# 7 switching on data types was fairly tricky. Luckily with the latest update we can do a C# switch on type very easily. Let's have a look below at why type switching is useful. We will also go over some code examples for both legacy C# and C# 7+.

Why switch on types?

Switching on an objects type is useful when you are executing different actions based for different types. The same can be achieved using if/else statements, though it tends to get a bit messy if you have more than two or three types. Let's check out a few examples below using the IVehicle interface. We will go over how to switch on types in both C# legacy and C# 7+.

Given the IVehicle interface and classes

Below we are using the IVehicle interface which requires both ApplyGas() & ApplyBreak() methods. For this example we implement the IVehicle interface via the Car and Truck classes. We did not implement a Vehicle base class but it would be possible to do so.

public interface IVehicle {
    void ApplyGas();
    void ApplyBrake();
}

public class Car : IVehicle {
void ApplyGas() {
// Apply car gas
};
void ApplyBrake() {
// Apply car brake
};
}

public class Truck : IVehicle {
void ApplyGas() {
// Apply truck gas
};
void ApplyBrake() {
// Apply truck brake
};
}

C# 7+ Switch

The cleanest way to type compare is to use a switch statement. We highly recommend upgrading to C# 7 to take advantage of the new pattern matching goodies as well. You can use traditional case statements to check the object type and execute the appropriate case block. In this example we will also throw an exception for the default case.

** If you get a compiler error, first check that you did not forget the break statement. 

Switching on Types using pattern matching

switch (vehicle)
{
case Car car:
WriteLine("Car!");
break;
case Truck truck:
WriteLine("Truck!");
break;
case null:
throw new ArgumentNullException();
break;
default:
// Anything other than Car, Truck or null
throw new UnknownVehicleException();
break;
}

Legacy C# Switch

Unfortunately on versions of C# prior to 7 we can't use case blocks. So we are stuck doing the type comparison ourselves. There are a few different ways to do this including the good old fashioned if/else statement. Let's go over a few examples using IVehicle below.

Switching on Types using if/elseif/else statements

Type vehicleType = vehicle.GetType();
if (vehicleType == null) {
throw new ArgumentNullException();
}
else if (vehicleType == typeof(Car)) {
WriteLine("Car!");
}
else if (vehicleType == typeof(Truck)) {
WriteLine("Truck!");
}
else {
throw new UnknownVehicleException()
}



Back to The Programmer Blog