I will say that the problem is resolved. I took the code from http://beardseye.blogspot.it/2007/08/nuts-enum-conundrum.html
enum TestEnum { e10, e9, e8, e7, e6, e5, e4, e3, e2, e1 } class Program { static void Main(string[] args) { Dictionary<TestEnum, int> dict = new Dictionary<TestEnum, int>(); for (int l = 0; l < 100000; l++) { TestEnum x = (TestEnum)(l % 10); dict[x] = 100000 - (int)x; } for (TestEnum x = TestEnum.e10; x <= TestEnum.e1; x++) { Console.WriteLine(dict[x]); } } }
And I ran it with the Visual Studio 2013 profiler. There are no TestEnum objects. "Note that if I changed the code to
dict[x] = 100000 - x.GetHashCode();
then I get a lot of TestEnum distributions.
Another test:
public class TestEnumComparer : IEqualityComparer<TestEnum> { public bool Equals(TestEnum x, TestEnum y) { return x == y; } public int GetHashCode(TestEnum obj) { return obj.GetHashCode(); } }
and
Dictionary<TestEnum, int> dict = new Dictionary<TestEnum, int>(new TestEnumComparer());
However, I get many TestEnum distributions.
So, I will say that EqualityComparer<T>.Default does something to not list the boxes.
If you look at the source of EqualityComparer in the CreateComparer() method:
// If T is an int-based Enum, return an EnumEqualityComparer<T> // See the METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST and METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST_LONG cases in getILIntrinsicImplementation if (t.IsEnum && Enum.GetUnderlyingType(t) == typeof(int)) { return (EqualityComparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumEqualityComparer<int>), t); }
there is some special code for comparing int enum and only them.
And I can confirm that if I change enum to
enum TestEnum : long
then the distributions caused by boxing appear !:-)
So at the end
Dictionary<enum_that_is_an_int, Foo>
safe
any other type of enum not !:-)
Note that this is true for .NET> = 4.0. I looked at CreateComparer() mscorlib 2.0.0.0, and there is no such check, so on the .NET 2.0-3.5 Dictionary<enum_that_is_an_int, Foo> not safe to use.