Multiple ways to check Key in Dictionary

Muhammad Waseem
Become .NET Pro !
2 min readFeb 13, 2023

How to check that key exists in a dictionary or not

1. Contains Key

It is most common way to check if a key exists or not in dictionary , it returns bool value.

2. Using Index way

It checks the key and if it is not found it will throw , key not found exception , use try catch to avoid it .

3. Using TryGetValue

It checks if the key exists or not and it will not throw the exception if value was not found.

4. Using custom extension method

You can create an extension method for your dictionary and check the key by iterating over dictionary via contains method

Here it is check example.

If you want to help the author in growing

  1. Subscribe my Weekly .NET Newsletter of C#/.NET
  2. Follow me on LinkedIn/Twitter OR Clap at least 50 times.
  3. Get exclusive .NET Questions & Answers by becoming a Patron.
  4. Download my eBook at Gumroad that contains 30 .NET Tips.

--

--