user3066571
user3066571

Reputation: 1471

initialize dictionary with enum, name does not exist in current context

I'm trying to create a dictionary using a string for the key and enum for the value. Code:

private enum Continent { Africa, Antarctica, Asia, Australia, Europe, NorthAmerica, SouthAmerica }

static void DemoDictionary()
{
    Console.WriteLine("\n\nDictionary Demo: (rivers)");
    Console.WriteLine("=========================\n");
    Dictionary<string, Continent> rivers = new Dictionary<string, Continent>()
    {
        {"Nile", Africa},
        {"Amazon", SouthAmerica},
        {"Danube", Europe}
    };
}

All of the Continent names are showing the name does not exist in the current context , and I'm not sure why. The private enum and the static Dictionary method need to stay put, so I need to work around that.

Upvotes: 2

Views: 2536

Answers (1)

Christos
Christos

Reputation: 53958

You should use this:

Continent.Africa 

instead of using this

Africa

This is happening, because the value of each key value pair item of your dictionary is of type Continent. If Africa was a variable, in which you had assigned the value of Continent.Africa everything would have been ok. Actually, the error message informs you that there isn't any variable called Africa in your context, let alone the issue of the type.

That being said, you should change your code to the following one:

 Dictionary<string, Continent> rivers = new Dictionary<string, Continent>()
 {
     {"Nile", Continent.Africa},
     {"Amazon", Continent.SouthAmerica},
     {"Danube", Continent.Europe}
 }; 

Upvotes: 5

Related Questions