views:

44

answers:

2
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?

+1  A: 

Only strings, integral types and enums can be used in .NET in a switch statement.

leppie
It's up to the language to decide what to support. You could certainly create a language targeting .NET which *did* support switching on Guids.
Jon Skeet
That's true for a C# switch statement. The .net switch instruction can only take integral types (enums being used through their integral value).
Jb Evain
leppie
+2  A: 

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.

Jon Skeet
Ahh, that make sense. Thanks!
Stringer Bell