Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify generic method type parameters partly

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");
like image 442
DNNX Avatar asked Nov 14 '22 11:11

DNNX


1 Answers

As long as you only use it on dictionaries of object, you can constrain T to be a reference type to make the cast valid:

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

  return (T)value;
}

But that's probably not what you want. Note that C# version 4 doesn't solve your problem either.

like image 151
Hans Passant Avatar answered Dec 16 '22 00:12

Hans Passant