C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The program populates the Dictionary with 2 key-value pairs. ContainsKey is invoked twice.
Argument: The ContainsKey method receives one parameter. This is the key we wish to check for.
Returns: ContainsKey returns a Boolean value that indicates whether the key was found in the Dictionary or not.
BoolAnd: You can test ContainsKey in an if-statement. It will not throw exceptions on a key that is not found.
IfTrue, FalseC# program that uses ContainsKey
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create Dictionary with two key value pairs.
var dictionary = new Dictionary<string, int>()
{
{"mac", 1000},
{"windows", 500}
};
// Use ContainsKey method.
if (dictionary.ContainsKey("mac") == true)
{
Console.WriteLine(dictionary["mac"]); // <-- Is executed
}
// Use ContainsKey method on another string.
if (dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false); // <-- Not hit
}
}
}
Output
1000
And: When it finds a matching hash code, it compares the key values and then returns the actual value.
Returns: The ContainsKey method discards some of the values it finds and simply returns a Boolean.
Therefore: Using TryGetValue can be used to perform these operations at one time, improving runtime speed.