C# – Check if key exists in Dictionary

This short post shows two (2) ways on how to check if a key exists in Dictionary. Dictionary is something similar to Map in Java.

Requirements

Stuffs used for this post.

  • SharpDevelop 5.1.0
  • .NET 4.6

Dictionary.ContainsKey(TKey)

.NET also has Generics similar to Java. The parameter TKey has T which means Generic type.

Outputs

Dictionary. TryGetValue(TKey, out TValue)

This method takes two (2) parameters. Again the parameter names are prefixed with T meaning they are of Generic Types.

This method is a bit special. The TValue must be preceded with out as the variable will be modified within TryGetValue and gets reflected on the valueFromMap1 and valueFromMap2.

Outputs

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert