Junior From PDF Collections C# Collections

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

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
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details