Why does the following code fail to compile, while changing the case statement to
case ENUM1: doSomeStuff();
works?
public enum EnumType
{
ENUM1, ENUM2, ENUM3;
void doSomeStuff()
{
switch(this)
{
case EnumType.ENUM1: doSomeStuff();
}
}
}
This is to avoid the ability to compare against different enum types. It makes sense to restrict it to one type, i.e. the type of the enum value in theswitchstatement.Update: it’s actually to keep binary compatibility. Here’s a cite from about halfway chapter 13.4.9 of JLS:
In other words, because of the class identifier in
EnumType.ENUM1, it cannot be represented as a compiletime constant expression, while it is required by theswitchstatement.