C# Dictionary Lookup Example

You want to access values at certain keys in your Dictionary. Comparing two common methods for lookup: ContainsKey and TryGetValue. Here we see the best ways of doing lookups on Dictionary instances in C# programs. Example Description In part A, it uses ContainsKey, which is helpful and tells us if something exists in the Dictionary. The inner part of the first if shows how the actual value is found: by another lookup.
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	Dictionary d = new Dictionary();
	d.Add("apple", true);
	d.Add("mango", false);
	d.Add("orange", true);

	// A.
	// We could use ContainsKey.
	if (d.ContainsKey("mango"))
	{
	    // Will be 'False'
	    bool result = d["mango"];
	    Console.WriteLine(result);
	}

	// B.
	// Or we could use TryGetValue.
	bool value;
	if (d.TryGetValue("mango", out value))
	{
	    // Will be 'False'
	    bool result = value;
	    Console.WriteLine(result);
	}
    }
}
Output False False