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

Viewed 12035

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

4 Answers

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

GetValueOrDefault() is part of ImmutableDictionary. so of course you get the error message. instead use

Dictionary.TryGetValue(TKey, TValue)

I use it in .Net Core (3.1)

class Dictionary<TKey, TValue> implements IReadOnlyCollection<KeyValuePair<TKey, TValue>>.

and there is and extension method in namespace System.Collections.Genericfor for IReadOnlyDictionary:

public static class CollectionExtensions
{
     ...
     public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) where TKey : notnull;
     ...
}

so we get it out of the box also for Dictionary<TKey, TValue>.

(Not sure about .net framework which going to be obsolete anyway)

When I encountered the same problem, I was just missing this:

using System.Collections.Generic

As mentioned by @guyarad, this is an extension method on IReadOnlyDictionary but it needs to be imported. It seems obvious, but since you can use a returned dictionary without the import, it can be confusing when it mostly works but is missing some functionality you're pretty sure it should have.

Related