X

C# tip use Dictionary TryGetValue

dotnet C#

Here is another C# tip.
Most of the time when you are trying to get a value from dictionary you would try to check if the key exist or not something like.

if(dictionary.ContainsKey(key))
{
  var value - dictionary[key];
 //do some stuff

}

But one can use TryGetValue

if(dictionary.TryGetValue(key, out value))
{
  //do stuff with value
}

The benefit of using TryGetValue is that the dictionary is synchronized, there is no race condition.

Categories: .NET C#
Taswar Bhatti:
Related Post