Search code examples
c#wpfdictionarynulltrygetvalue

TryGetValue returns Null even though key exists?


I have a few dictionary objects being combed through to get a value but all of them return null even though when I check to see if they contain the key the one that has the key returns true. I can also use a foreach to go through each one to get the value based on that key....I'm so lost

foreach (var item in treeView.SelectedItems)
{
    string reportName = item.Header.ToString();
    string reportPath = "";

    reportsAvail.TryGetValue(reportName, out reportPath);
    reports.TryGetValue(reportName, out reportPath);
    additionalReports.TryGetValue(reportName, out reportPath);

    bool test; 

    test = reportsAvail.ContainsKey(reportName);
    test = reports.ContainsKey(reportName);
    test = additionalReports.ContainsKey(reportName);

    foreach (var y in reportsAvail)
    {
        if (y.Key.ToString() == reportName)
        {
            textBlock1.Text = y.Value;
            reportPath = y.Value;
        }
    }
}

What's weird is it USED to work...I'm not sure what's stopping it


Solution

  • You are using TryGetValue three times and you're overwriting reportPath each time. So even if the first or second contained the reportName, if the third didn't contain it reportPath will be null again.

    Maybe this fixes it:

    bool reportFound = reportsAvail.TryGetValue(reportName, out reportPath);
    if(!reportFound)
        reportFound = reports.TryGetValue(reportName, out reportPath);
    if(!reportFound)
        reportFound = additionalReports.TryGetValue(reportName, out reportPath);