This post will discuss how to determine whether a key exists in a Dictionary in C#.

1. Using ContainsKey() method

We can use the ContainsKey() method to determine whether the Dictionary contains an element with the specified key. The following example demonstrates this.

Download  Run Code

2. Using Dictionary.TryGetValue() method

TryGetValue() method returns true if the Dictionary contains an element with the specified key; otherwise, false. This is demonstrated below:

Download  Run Code

That’s all about checking if a key exists in a Dictionary in C#.