I can define an enum with integer as value:
public enum FieldType
{
Bar = 0,
Foo = 1
}
Why C# doesn't allow creating a dictionary with integer as a key and using an enum value when creating:
public Dictionary<int, Type> _fieldMapping = new Dictionary<int, Type>
{
{FieldType.Bar, null}, # Error in VS
{FieldType.Foo, null}, # Error in VS
}
I know i can do a cast, but i would like to know why enum cannot be converted to int implicitly when it actually is int under the hood.
If you could do that, you'd lose half the point of using enums at all - the point is to keep them as separate types to avoid you making mistakes involving using types incorrectly.
It seems to me like your dictionary should actually have FieldType
as the key - at which point you'd have a safer approach. With your current expectation, you're expecting to be able to use any (int
-based) enum type as the key, including things like FileShare
which are clearly inappropriate.
So basically, you should ask yourself whether fundamentally you've got a map from field type to type, or whether you've really got a numeric map. To put it another way, without looking at FieldType
at all, does an entry in the map from the number 1 to some Type
mean anything? What does the 1 value represent there?
See more on this question at Stackoverflow