Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cant use dictionary outside function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"}};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading