Freakish Type System Issues

time to read 2 min | 387 words

Take a guess, what is going to be the result of the following code?

Enum one = DayOfWeek.Sunday;

Enum two = DayOfWeek.Sunday;

Assert.IsTrue(one == two);

Update: Tomas Restrepo, hit the nail on the head in the comments.

System.Enum is a reference type. The first line actually translates to:

L_0001: ldc.i4.0
L_0002: box [mscorlib]System.DayOfWeek
L_0007: stloc.0

There is boxing done here, and then the == is doing reference equality. I actually learned about this from Tomas, a while ago, when discussing about wierd-ass questions.

This is a freakish issue because Enum inherits from ValueType, so you would expect it to keep value types semantics. Check the comments for Tomas' for explanation