Flynn1179
Flynn1179

Reputation: 12075

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?

Upvotes: 5

Views: 1209

Answers (3)

svick
svick

Reputation: 244767

If you are set on using switch on Type, I think you have few choices, both fairly poor.

The first option is to use TypeCode, e.g.:

switch (Type.GetTypeCode(propType))
{
  case TypeCode.Byte:
    // Do something
    break;
}

This approach is severely limited, since it supports only the few built-in types that are in the TypeCode enum.

Another option is to switch on the type name:

switch (propType.FullName)
{
  case "System.Byte":
    // Do something
    break;
}

This is not great either, since you have to write the full name including namespace, the name is not checked for typos and such switch would also accept "fake" System.Byte type (i.e. a custom type named System.Byte, not the one included in .Net).

Upvotes: 0

David Arno
David Arno

Reputation: 43254

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;
}

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 156948

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.

Upvotes: 3

Related Questions