Enabling Type Variable

It sounds like it should be very simple, but I just don't see a way to make this 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 to do

private const byteType = typeof(byte);

and enable it, but this line of code does not compile for the same reason.

So the question is: how to enable the instance Type?

+6
source share
3 answers

Well, my original answer was wrong. You cannot do this in a type switch (without using when, as indicated, which is terrible for this using, in my opinion). The problem is that Typeit is not a constant, so you cannot use this on a switch.

, , Type. if.

+3

switch, var when guard:

Type propType = propertyInfo.PropertyType;
switch (propType)
{
    case var b when b == typeof(byte):
        // Do something
        break;
}
+2

switch Type, , , .

- TypeCode, :

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

, , TypeCode.

- :

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

, , , , switch "" System.Byte (.. System.Byte, , .Net).

0

Source: https://habr.com/ru/post/1016747/


All Articles