C#, Software Development

C# – Check if key exists using these Dictionary Methods

C# key exist Dictionary

A well-rounded software developer could easily switch between programming languages. Besides, full-stack developers do this already. They have skills for both backend and frontend. Therefore, we should learn another language like C# no matter what programming language forte we come from. This post shows two ways how to check if a key exists in C# Dictionary, which is akin to Map in Java or associative arrays in PHP.

C# Requirements

We used the following items for this post.

  • SharpDevelop 5.1.0
  • .NET 4.6

Alternatively, we could use the Rider IDE from JetBrain, or MVC from Microsoft.

Check For Keys With Dictionary ContainsKey(TKey) Method

The .NET has Generics similar to Java, and the parameter name we see in the documentation indicates Generic types. For example, consider the following method signature.

The T in the parameter name gives away the parameter type.

When we run the C# codes, we get the following output.

Check For Keys using C# Dictionary TryGetValue(TKey, out TValue)

Alternatively, we could use the TryGetValue method, but it takes two (2) arguments of Generic types. This method is somewhat unique because we need to use the out keyword with the TValue parameter. The method allows us to get the value we set for a key. In summary, the TryGetValue method will enable us to get more information by returning True or False and the value, if it exists, for a key.

When we run the codes, we get the following result. As we can see, the C# codes check if a key exists in a Dictionary and returns its value if available. Otherwise, we get an empty (or null even) string value. Therefore, we get two values for a single method call.

Are there other ways for C# to check if a key exists in a Dictionary? We would love to hear from you.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like