Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum as Dictionary keys

Tags:

c#

.net-2.0

Suppose to have

enum SomeEnum { One, Two, Three };

SomeEnum is an enum so it is supposed to inherit from Enum so why if I write:

Dictionary<Enum, SomeClass> aDictionary = new Dictionary<SomeEnum, SomeClass>();

The compiler complains that it cannot implicitly convert SomeEnum to Enum?

like image 417
sblandin Avatar asked Sep 10 '13 10:09

sblandin


People also ask

Is enum a dictionary in python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.

Is an enum a dictionary?

Dictionaries store unordered collections of values of the same type, which can be referenced and looked up through a unique identifier (also known as a key). An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

Should I use enum in Python?

Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc. They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.

What is an enum TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.


1 Answers

I believe that's because of covariance.

In short:

aDictionary will be a Dictionary<SomeEnum, SomeClass>, but in the current context it is known as Dictionary<Enum, SomeClass>.

Had your declaration been allowed, the compiler should afterwards let you do:

aDictionary.Add(someValueFromAnotherEnumUnrelatedToSomeEnum, aValue);

which is obviously inconsistent with respect to the actual type of the dictionary.

That's why co-variance is not allowed by default and you have to explicitly enable it in cases where it makes sense.

The conclusion is that you have to specify the type exactly:

Dictionary<SomeEnum, SomeClass> aDictionary = 
    new Dictionary<SomeEnum, SomeClass>();
like image 65
Cristian Lupascu Avatar answered Sep 20 '22 02:09

Cristian Lupascu