How to use switch statement with class

The switch statement controls the execution flow using comparison of constant values. This implies that in each case, the possible values are of primitive or Enum types. What can we do if we want to use a custom class as the switch expression? Clearly this is impossible by default, since custom classes are not primitives or Enums. The solution is to use the implicit cast.

Implicit cast

Implicit cast can is implemented using the implicit cast operator. Implicit cast enables, for example, assignment of instance from one type into a variable of other type.

Example of implicitly castable class:

public class Person
{
public string ID { get; set; }

static public implicit operator int (Person person)
{
return int.Parse(person.ID.Substring(0, 1));
}
}

This casting allows this simple assignment:

var person = new Person() {ID = "0-12345678-9"};
int quality = person;

Switch on class

In order to use a class instance as the switch expression we must choose a governing type for the cases (primitive or Enum) and make the original class castable to that type. For example, if we choose a class of type Person and governing type int then we must have an implicit cast from Person to int.

For example, using the class Person:

var person = new Person() {ID = "0-12345678-9"};

switch (person)
{
case 0:
Console.WriteLine("This is a top level person");
break;
case 9:
Console.WriteLine("This is a bottom level person (probably a developer)");
break;
default:
Console.WriteLine("Just a regular person");
break;
}
Advertisement