I am wondering why it is that a single implicit conversion to an enum value doesn't work the same way it would if the conversion were to a system type. I can't see any technical reason however maybe someone smarter than I can shed some light for me.
The followoing fails to compile with, "A value of an integral type expected"
and "Cannot implicitly convert type 'Test.En' to 'Test.Foo"
.
void test1 (){
Foo f = new Foo();
switch (f) // Comment this line to compile
//switch ((En)f) // Uncomment this line to compile
{
case En.One:
break;
}
}
//////////////////////////////////////////////////////////////////
public enum En
{
One,
Two,
Three,
}
public class Foo
{
En _myEn;
public static implicit operator En(Foo f)
{
return f._myEn;
}
}
edit from the spec:
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.
To Clarify the question, why is an enum-type not included with the list of allowed user-defined implicit conversions?