Search code examples
c++-cliswitch-statementtypeid

Why switch expressions of type 'System::Guid' are illegal?


void Foo(Type^ type)
{
  System::Guid id = type->GUID;
  switch (id)
  {
  case System::Byte::typeid->GUID:
    ...
    break;
  ...
  }

Obviously case expressions are not constant. But I'd like to know why GUIDs cannot be known at compile time? (silly question I guess).

At the end of the day it looks you have to use imbricated if then else for testing against typeid and thats the only way to go, right?


Solution

  • Simply put: the CLR has no metadata representation of a Guid... or indeed DateTime or Decimal, as the other obvious candidates. That means there isn't a constant representation of Guid, and switch cases have to be constants, at least in C# and I suspect in C++/CLI too.

    Now that doesn't have to be a blocker... C# allows const decimal values via a fudge, and languages could do the same thing for Guids, and then allow you to switch on them. The language can decide how it's going to implement switching, after all.

    I suspect that the C++/CLI designers felt that it would be a sufficiently rare use-case that it wasn't worth complicating the language and the compiler to support it.