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?