I have this method
public string DictionaryToString<T, U>(Dictionary<T, U> dict)
{
var valueStrings = dict.Select(x => x.Key.ToString() + ": " + x.Value.ToString());
return String.Join("\n", valueStrings);
}
And I have this object that I want to pass into it
if ((value !=null) && value.GetType().IsGenericType &&
value.GetType().GetGenericTypeDefinition() == typeof (Dictionary<,>))
{
var castValue = value as Dictionary<,>; // this cast does not work
return DictionaryToString(castValue);
}
else
{
return value.ToString();
}
I can use reflection code like this in .Net 4.5
var targetMethodInfo = typeof(MyType).GetMethod("DictionaryToString");
var valueTypeArgs = value.GetType().GenericTypeArguments;
var genericMethod = targetMethodInfo.MakeGenericMethod(valueTypeArgs);
var result = genericMethod.Invoke(this, new[] {value });
return result.ToString();
ButType.GenericTypeArguments is new in .Net 4.5. So how can I do that cast in .Net 4.0?
You are only calling
ToStringon the key and value, so simply have this method take anIDictionary(non-generic), you are not using anything in there that is type-specific toTorU.You can then simply cast all arguments to
IDictionary:You may also need to amend the
DictionaryToStringimplementation:Alternatively, if you really want to use LINQ, you could try casting to
dynamic(it isn’t possible to cast to anything else as this could be a generic dictionary (KeyValuePair<>) or non-generic hashtable (DictionaryEntry)):This basically “duck types” the existence of the
KeyandValueproperties.