You cannot use a switch block to test values of type Type
. Compiling your code should give you an error saying something like:
A switch expression or case label must be a bool, char, string,
integral, enum, or corresponding nullable type
You’ll need to use if
–else
statements instead.
Also: typeof(int)
and typeof(Int32)
are equivalent. int
is a keyword and Int32
is the type name.
UPDATE
If you expect that most types will be intrinsic you may improve performance by using a switch block with Type.GetTypeCode(...)
.
For example:
switch (Type.GetTypeCode(type))
{
case TypeCode.Int32:
// It's an int
break;
case TypeCode.String:
// It's a string
break;
// Other type code cases here...
default:
// Fallback to using if-else statements...
if (type == typeof(MyCoolType))
{
// ...
}
else if (type == typeof(MyOtherType))
{
// ...
} // etc...
}