I have a function in C# that operates on generic Dictionary’s:
public static string DoStuff<TKey, TValue>(Dictionary<TKey, TValue> dictionary)
{
// ... stuff happens here
}
I also have a function that loops over objects. If one of those objects is a Dictionary<>, I need to pass it to that generic function. However, I won’t know what the types for the Key or Values are at compile-time:
foreach (object o in Values)
{
if (/*o is Dictionary<??,??>*/)
{
var dictionary = /* cast o to some sort of Dictionary<> */;
DoStuff(dictionary);
}
}
How do I do this?
Assuming you can’t make your method generic in the type of the
Valuescollection, you can use dynamic:Alternatively you can use reflection: