Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching on a type variable

This feels like it should be really easy, but I just can't see a way to get this to work.

Type propType = propertyInfo.PropertyType;
switch (propType)
{
  case typeof(byte): // Can't do this, 'A constant value is expected'
    // Do something
    break;
}

I also tried doing

private const byteType = typeof(byte);

and switching on that, but this line of code fails to compile for the same reason.

So, the question: How do I switch on an instance of Type?

like image 734
Flynn1179 Avatar asked Apr 25 '17 09:04

Flynn1179


People also ask

What is switch on type?

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.

What is switch expression in c#?

In C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.


2 Answers

Okay, my initial answer was wrong. You can't do that in a type switch (without using when as pointed out, which is awful for this use in my opinion). The problem is that a Type is not a constant, so you can't use that in a switch.

I was mistaken because you weren't using the actual value but a Type instance. You have to keep using if statements.

like image 149
Patrick Hofman Avatar answered Sep 29 '22 08:09

Patrick Hofman


You can do this with switch, you just need to use a var pattern and when guard:

Type propType = propertyInfo.PropertyType;
switch (propType)
{
    case var b when b == typeof(byte):
        // Do something
        break;
}
like image 23
David Arno Avatar answered Sep 29 '22 07:09

David Arno