Not able to use GetValueorDefault() for Dictionary in C#

  • A+

I've defined a Dictionary with some custom type like this,

 public readonly Dictionary<PricingSection, View> _viewMappings = new Dictionary<PricingSection, View>(); 

Now when i try to do


section is of type PricingSection

i'm getting an error saying

Severity Code Description Project File Line Suppression State Error CS1061 'Dictionary' does not contain a definition for 'GetValueOrDefault' and no accessible extension method 'GetValueOrDefault' accepting a first argument of type 'Dictionary' could be found (are you missing a using directive or an assembly reference?)

Am i missing something ??


Am i missing something ??

You are missing the fact Dictionary does not contain any method of this name GetValueOrDefault

Dictionary Class

Maybe you are looking for

Dictionary.TryGetValue(TKey, TValue) Method

Gets the value associated with the specified key.


ImmutableDictionary.GetValueOrDefault Method (IImmutableDictionary, TKey)

Gets the value for a given key if a matching key exists in the dictionary.

You could however implement your own

public static class Extensions {     public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict,TKey key)       =>  dict.TryGetValue(key, out var value) ? value : default(TValue); } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: