'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 1:[1]
GetValueOrDefault() is part of ImmutableDictionary. so of course you get the error message. instead use
Dictionary.TryGetValue(TKey, TValue)
Solution 2:[2]
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.
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Benjamin Smith |
| Solution 3 | Aviko |
