get dictionary value by key

How can I get the dictionary value by key on function?

My function code (and the command I try doesn’t work):

static void XML_Array(Dictionary<string, string> Data_Array)
    String xmlfile = Data_Array.TryGetValue("XML_File", out value);

My button code:

private void button2_Click(object sender, EventArgs e)
    Dictionary<string, string> Data_Array = new Dictionary<string, string>();
    Data_Array.Add("XML_File", "Settings.xml");


I want on XML_Array function the variable to be:

string xmlfile = "Settings.xml":


It’s as simple as this:

String xmlfile = Data_Array["XML_File"];

Note that if the dictionary doesn’t have a key that equals "XML_File", that code will throw an exception. If you want to check first, you can use TryGetValue like this:

string xmlfile;
if (!Data_Array.TryGetValue("XML_File", out xmlfile)) {
   // the key isn't in the dictionary.
   return; // or whatever you want to do
// xmlfile is now equal to the value

Leave a Reply

Your email address will not be published. Required fields are marked *