sharp-soft
sharp-soft

Reputation: 23

Compile error trying to initialize Dictionary<T,U> with elements

I have an Enum type e.g.

    enum MyEnum
    {
        V1,
        V2,
        V3
    }

And I want to add each element to a dictionary as Keys with additional data:

        Dictionary<MyEnum, string> dictionary = new Dictionary<MyEnum, string>()
        {
            new KeyValuePair<MyEnum, string>(MyEnum.V1, "");
        };

But it cause compile error. However it works with a List.

List<MyEnum> list = new List<MyEnum>() { MyEnum.V1, MyEnum.V3 };

How can I make the Dictionary example work?

Upvotes: 0

Views: 27

Answers (1)

Major
Major

Reputation: 6688

You don't need the KeyValuePair<MyEnum, string> Just use this:

        Dictionary<MyEnum, string> dictionary = new Dictionary<MyEnum, string>()
        {
            { MyEnum.V1, "" },
            { MyEnum.V2, "" }
        };

Upvotes: 1

Related Questions