Problem with writing type of generalized extension method writing

I really hate sometimes when it IDictionary<TKey, TValue> [key]throws an exception if the key does not exist in the dictionary.

Of course there is TryGetValue(), but it seems to be optimized for performance, and not for ease of use.

So, I thought, oh, I'll just do an extension method for it - what I did:

public static class CollectionExtensions
{
    public static TType GetValueOrDefault<TKeyType, TValue, TType>(this IDictionary<TKeyType, TType> dictionary, TKeyType key)
    {
        TType value = default(TType);

        // attempt to get the value of the key from the dictionary
        // if the key doesn't exist just return null
        if (dictionary.TryGetValue(key, out value))
        {
            return value;
        }
        else
        {
            return default(TType);
        }
    }    
}

This works fine EXCEPTION I cannot get it to work with the output type.

Obviously, I want to be able to do the following:

var extraDataLookup = new Dictionary<string, string>();
extraDataLookup["zipcode"] = model.Zipcode; 

and then access the value:

var zipcode = extraDataLookup.GetValueOrDefault("zipcode");
var foo = extraDataLookup.GetValueOrDefault("foo"); // should be null

I looked at a few things about type inferences by introducing a Jon Skeet article and even the source code into System.Linq.Enumerablea reflector , but there seems to be something missing.

It works:

extraDataLookup.GetValueOrDefault<string, string,string> ("foo") 

But it is not

extraDataLookup.GetValueOrDefault ("foo") 

What should I do.

PS. , . .

+3
1

, , . "TValue" "TType" , ? :

public static TValue GetValueOrDefault<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary, TKey key)
{
    TValue value;
    // attempt to get the value of the key from the dictionary
    dictionary.TryGetValue(key, out value);
    return value;
}    
+5

Source: https://habr.com/ru/post/1702617/


All Articles