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");