How to specify generic method type parameters partly

Posted by DNNX on Stack Overflow See other posts from Stack Overflow or by DNNX
Published on 2010-04-06T12:24:37Z Indexed on 2010/04/06 13:03 UTC
Read the original article Hit count: 206

I have an extension method like below:

public static T GetValueAs<T, R>(this IDictionary<string, R> dictionary, string fieldName)
    where T : R
{
    R value;
    if (!dictionary.TryGetValue(fieldName, out value))
        return default(T);

    return (T)value;
}

Currently, I can use it in the following way:

    var dictionary = new Dictionary<string, object>();
    //...
    var list = dictionary.GetValueAs<List<int>, object>("A"); // this may throw ClassCastException - this is expected behavior;

It works pretty fine, but the second type parameter is really annoying. Is it possible in C# 4.0 rewrite GetValueAs is such a way that the method will still be applicable to different types of string-keyed dictionaries AND there will be no need to specify second type parameter in the calling code, i.e. use

    var list = dictionary.GetValueAs<List<int>>("A");
or at least something like
    var list = dictionary.GetValueAs<List<int>, ?>("A");
instead of
    var list = dictionary.GetValueAs<List<int>, object>("A");

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics