Skip to main content

How to Get a Dictionary Value or a Default with GetValueOrDefault in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Reading a Dictionary with dictionary[key] throws when the key isn't there. When a missing key simply means "nothing", GetValueOrDefault is shorter and safer: it gives you the value if there is one, and a default if there isn't.

Syntax​

Syntax
<ValueType>? <value> = <dictionary>.GetValueOrDefault(<key>);
<ValueType> <value> = <dictionary>.GetValueOrDefault(<key>, <defaultValue>);
PartWhat it does
GetValueOrDefault(<key>)The value for the key, or the value type's default when the key isn't there: null for a string, 0 for an int
GetValueOrDefault(<key>, <defaultValue>)The same, but returns your <defaultValue> when the key isn't there

Microsoft's GetValueOrDefault reference describes both: "Tries to get the value associated with the specified key in the dictionary." Without a default, "When the method fails, it returns the default value for TValue." With one, "When the method fails, it returns defaultValue."

The Example​

An office keeps who sits at which desk, and how many times each person visited. Ana has a desk and 3 visits; Ben has neither. The program asks for both, with and without a default.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which stores Desk 4 for Ana in a desks dictionary and prints GetValueOrDefault for Ana, for Ben with a fallback of no desk, and for Ben with the default Front desk, then stores 3 visits for Ana and prints GetValueOrDefault for Ana and for Ben.

main.cs
Dictionary<string, string> desks = [];
desks["Ana"] = "Desk 4";

Console.WriteLine(desks.GetValueOrDefault("Ana"));
Console.WriteLine(desks.GetValueOrDefault("Ben") ?? "(no desk)");
Console.WriteLine(desks.GetValueOrDefault("Ben", "Front desk"));

Dictionary<string, int> visits = [];
visits["Ana"] = 3;

Console.WriteLine(visits.GetValueOrDefault("Ana"));
Console.WriteLine(visits.GetValueOrDefault("Ben"));

?? gives the value on its right when the one on its left is null.

Step 2: Run It​

Terminal
dotnet run main.cs
Output
Desk 4
(no desk)
Front desk
3
0

A zsh terminal where dotnet run main.cs prints Desk 4, (no desk), Front desk, 3 and 0.

  1. Ana is there, so both dictionaries gave her value: Desk 4 and 3.
  2. Ben's desk came back as null, a string's default, which ?? turned into (no desk).
  3. With "Front desk" as the default, Ben got that instead.
  4. Ben's visits came back as 0, an int's default. Nothing threw.

The command is the same in zsh, bash and PowerShell.

When 0 Is a Real Value​

The default and a stored value can look exactly the same. Here Cy really has 0 visits, and Ben isn't in the dictionary at all:

main.cs
Dictionary<string, int> visits = [];
visits["Cy"] = 0;

Console.WriteLine(visits.GetValueOrDefault("Cy"));
Console.WriteLine(visits.GetValueOrDefault("Ben"));
Console.WriteLine(visits.TryGetValue("Cy", out int cy) ? $"Cy: {cy}" : "Cy: not there");
Console.WriteLine(visits.TryGetValue("Ben", out int ben) ? $"Ben: {ben}" : "Ben: not there");
Output
0
0
Cy: 0
Ben: not there

GetValueOrDefault printed 0 for both. TryGetValue returns true or false as well as the value, so it told them apart. Use it when "missing" and "zero" mean different things.

Common Mistakes​

MistakeWhat happensDo this instead
Using GetValueOrDefault when 0 or null can be a stored valueA missing key and a stored default look the sameUse TryGetValue
Forgetting that a string value's default is nullThe result is null, and reading a member of it throwsPass a default, or use ??
Reading with the indexer, desks["Ben"], for a key that may be missingKeyNotFoundExceptionUse GetValueOrDefault

Troubleshooting​

SymptomLikely causeFix
A missing key gives 0 or nothing at allThat's the value type's defaultPass your own default as the second argument
error CS0411: The type arguments for method 'CollectionExtensions.GetValueOrDefault...' cannot be inferred from the usageThe variable's type is IDictionaryThe fix

FAQ​

Do I need a using directive for GetValueOrDefault?​

Not in a project with implicit usings, which includes a file run with dotnet run: the example above has none. The method lives in CollectionExtensions, in the System.Collections.Generic namespace, which those usings include.

Does GetValueOrDefault add the key?​

No. It only reads. After desks.GetValueOrDefault("Ben", "Front desk"), the dictionary still had 1 entry, and ContainsKey("Ben") was False.

Conclusion​

dictionary.GetValueOrDefault(key) returns the value, or null or 0 when the key is missing, and GetValueOrDefault(key, fallback) returns your fallback instead. When a stored default must be told apart from a missing key, use TryGetValue.

Additional Resources​