0

I am trying to define an extension method in C# which would allow me to get a value by key from a dictionary, but which would return null instead of throwing in case of missing values (this is from inside a static utility class):

public static Value? Get<Key, Value>(this Dictionary<Key, Value> from, Key by)
    where Value : struct
{
    Value result;
    return from.TryGetValue(by, out result) ? result : (Value?)null;
}

public static Value Get<Key, Value>(this Dictionary<Key, Value> from, Key by)
        where Value : class
{
    Value result;
    return from.TryGetValue(by, out result) ? result : null;
}

Both of these appear to compile individually. But put together, the compiler says: "Type already defines a member with same parameter types". In reality, they don't have because Value is a value type in upper and a reference type in lower one.

Is there a way to make this work without having to change the method call between ref/value types? Or have I hit the limit of language expressiveness here?

dukc
  • 121
  • 1
  • 9
  • The simple solution is just to use different names for the two methods. – juharr Sep 21 '17 at 13:00
  • But that would mean changing the call if type of the dictionary value changes. But look the best answer in the theard this appears to be duplicate of. That's a MacGyver solution if any! – dukc Sep 21 '17 at 13:39
  • And if the dictionary value type changes you have to change what you pass to the method, so how's that better? – juharr Sep 21 '17 at 13:41
  • For example, the dictionary may well be defined like var dict = anEnumerable.ToDictionary(x => x.Id); Now I can call dict.Get(someId) without minding whether elements of anEnumerable have reference or value semantics. – dukc Sep 22 '17 at 14:26

0 Answers0