Search code examples
c#dictionaryxamarin.forms.net-standard

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


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

_viewMappings.GetValueOrDefault(section);

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 ??


Solution

  • Am i missing something ??

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

    Dictionary<TKey,TValue> Class

    Maybe you are looking for

    Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) Method

    Gets the value associated with the specified key.

    or

    ImmutableDictionary.GetValueOrDefault<TKey, TValue> Method (IImmutableDictionary<TKey, TValue>, 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);
    }
    

    If you are using any of the following, there are extension method overloads for IReadOnlyDictionary

    • NET 5.0 RC1

    • .NET Core 3.1 3.0 2.2 2.1 2.0

    • .NET Standard 2.1

    CollectionExtensions.GetValueOrDefault

    Tries to get the value associated with the specified key in the dictionary