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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With