Junior Collections

What is the difference between TryGetValue() and indexer access in a Dictionary?

Feature TryGetValue() Indexer (dictionary[key])

Safe? Yes – avoids exception No – throws if key doesn't exist

Returns Boolean (and output

value)

Direct value

Use

case

When unsure if key exists When key is guaranteed to

exist

Example:

if (dictionary.TryGetValue("Bob", out int age)) {

Console.WriteLine(age);

// dictionary["Unknown"]; // throws KeyNotFoundException if missing

More from C# Programming Tutorial

All questions for this course