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
?
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With