I have the code below in which there are 2 enums and a function that takes base class Enum as parameter, casts the general Enum to SomeEnum and displays it. I would have expected that when you pass SomeOtherEnum in the function, a InvalidCastException to be thrown because I was suspecting that the compiler generates for every enum another type. From the behavior however, it seems that the compiler has a single generated class type and every instance has different parameters(the enums). Is this correct? If not, why is it possible to pass seemingly incompatible types and the compiler doesn't complain?
'
enum SomeEnum
{
X1,
X2,
X3
}
enum SomeOtherEnum
{
X1,
X2,
X3,
X4,
X5
}
public static void SomeFunction(Enum someEnum)
{
SomeEnum x = SomeEnum.X3; // some dummy init
try
{
x = (SomeEnum) someEnum;
}
catch (InvalidCastException)
{
Console.WriteLine("Exception"); // why no exception caught ? why legit cast ?
}
Console.WriteLine(x);
}
private static void Main(string[] args)
{
SomeFunction(SomeOtherEnum.X5); // pass a different type than the one in the function
Console.ReadKey();
}
`