Dictionary GetValueOrDefault Method
This page was last reviewed on Oct 25, 2023.
Dot Net Perls
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).
Dictionary ContainsKey
Dictionary TryGetValue
Example. 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.
Part 1 We create a Dictionary of string keys, and integer values. Don't worry too much about the contents of this Dictionary.
Part 2 We get a value that exists in the Dictionary of concepts. We print that value, which is 10.
Part 3 We get a value that does not exist, and 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
Streamline code. 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.
Step 1 We create a Dictionary to test with, and this Dictionary has just one key and one value.
Step 2 With foreach, we sum up the values for the keys in an array. If a key is not found, the default value 0 is returned.
Step 3 We display our results. This program shows that when we can handle the default value, 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);
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 25, 2023 (new).
© 2007-2024 Sam Allen.