How to switch on System.Type?

The (already linked) new pattern matching feature allows this.

Ordinarily, you’d switch on a value:

switch (this.value) {
  case int intValue:
    this.value = Math.Max(Math.Min(intValue, Maximum), Minimum);
    break;
  case decimal decimalValue:
    this.value = Math.Max(Math.Min(decimalValue, Maximum), Minimum);
    break;
}

But you can use it to switch on a type, if all you have is a type:

switch (type) {
  case Type intType when intType == typeof(int):
  case Type decimalType when decimalType == typeof(decimal):
    this.value = Math.Max(Math.Min(this.value, Maximum), Minimum);
    break;
}

Note that this is not what the feature is intended for, it becomes less readable than a traditional ifelse ifelse ifelse chain, and the traditional chain is what it compiles to anyway. I do not recommend using pattern matching like this.

Leave a Comment