GetValueOrDefault
It is possible to access values with a key in a C# Dictionary
with TryGetValue
. But for many programs, GetValueOrDefault
is simpler and clearer to use.
With this method, we get the requested value if the key exists in the Dictionary
. And if does not exist, we receive a default value (like 0 for ints).
To begin we must generate a simple Dictionary
to test the GetValueOrDefault
method with. We try to access keys that exist, and do not exist.
Dictionary
of string
keys, and integer values. Don't worry too much about the contents of this Dictionary
.Dictionary
of concepts. We print that value, which is 10.GetValueOrDefault
steps in and returns the value 0 instead of some sort of error.using System; using System.Collections.Generic; // Part 1: create Dictionary. var concepts = new Dictionary<string, int>() { { "truth", 10 }, { "freedom", 50 }, { "love", 200 }, }; // Part 2: get a value that exists. var result = concepts.GetValueOrDefault("truth"); Console.WriteLine($"truth: {result}"); // Part 3: get a value that does not exist. result = concepts.GetValueOrDefault("nothing"); Console.WriteLine($"nothing: {result}");truth: 10 nothing: 0
Suppose you have a loop that can handle the default value in an elegant way. For example, if we are summing values in a Dictionary
, 0 can be used to mean nothing.
Dictionary
to test with, and this Dictionary
has just one key and one value.foreach
, we sum up the values for the keys in an array. If a key is not found, the default value 0 is returned.GetValueOrDefault
can lead to more elegant code.using System; using System.Collections.Generic; // Step 1: create dictionary. var test = new Dictionary<string, int>() { { "bird", 10 } }; // Step 2: sum up the values for all these keys if they exist. // ... Add 0 (the default value) if not found. var items = new string[]{ "bird", "frog", "dog" }; var sum = 0; foreach (var item in items) { sum += test.GetValueOrDefault(item); } // Step 3: print the result. Console.WriteLine(sum);10
In many C# programs, GetValueOrDefault
may be the best way to access values from a Dictionary
. It can reduce code size, by moving a branch into a separate method.