Joan Venge Joan Venge -4 years ago 180
C# Question

Why doesn't C# switch statement allow using typeof/GetType()?

As in this example:

switch ( myObj.GetType ( ) )
{
case typeof(MyObject):
Console.WriteLine ( "MyObject is here" );
break;
}

Answer Source

The problem is that switch (per the spec) only works with primitives (int etc) and strings. But yes, it would be nice to have F#-style matching.

From §8.7.2:

switch-label:
   case   constant-expression   :
   default   :

... The governing type of a switch statement is established by the switch expression. If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type, then that is the governing type of the switch statement. Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.

It is obvious, however, that working with such a restricted set allows for simple (and efficient) IL. Note that string is handled via a dictionary map to an integer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download