7
votes

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

3
But why do you think that Dictionary contains that method?Yurii N.
you provided method for ImmutableDictionary which is absolutely different from simple Dictionary.Yurii N.
In NETCore 2.2 it's an extension method for IReadOnlyDictionary which Dictionary implements. So this will work for 2.2.Guy

3 Answers

16
votes

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

1
votes

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

Dictionary.TryGetValue(TKey, TValue)

0
votes

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.