Home > OS >  Cant use dictionary outside function
Cant use dictionary outside function

Time:06-30

Situation is as following: I am trying to use an dictionary in C# (.NET Framework in Visual Studio) point is that whenever I put the Dictionary outside of an function it does not seem to work.

This is how I would want it to be:

public Form1()
{
    InitializeComponent();
}

Dictionary<string, string> countriesMap = new Dictionary<string, string>();
countriesMap.Add("Parijs", "7,13");

public void Form1_Load(object sender, EventArgs e)
{
    FormBorderStyle = FormBorderStyle.None;
    WindowState = FormWindowState.Maximized;
    locater();
}

This is how I am now doing this, but this is inconvenient since I need to use the dictionary in multiple functions.

private string randomGetter()
{
    Dictionary<string, string> countriesMap = new Dictionary<string, string>();
    countriesMap.Add("Parijs", "7,13");
}

Is there something wrong with my VS setup or is this just not possible and should I work around it?

CodePudding user response:

The add method call has to be inside a method or constructor. You could add it as part of your dictionary initializer.

public Form1()
{
    InitializeComponent();
    countriesMap.Add("Parijs", "7,13");
}

Dictionary<string, string> countriesMap = new Dictionary<string, string>();

As part of the initializer would look like:

Dictionary<string, string> countriesMap = new Dictionary<string, string>(){{"Parijs", "7,13"}};

CodePudding user response:

Oh I see, that does indeed solve the problem! Thanks for your help!

  • Related