Cast object to a Dictionary<TKey, TValue>

c#, dictionary, generics

Solution

Assuming you can't make your method generic in the type of the `Values` collection, you can use dynamic:

foreach (object o in values)
{
    Type t = o.GetType();
    if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>))
    {
        string str = DoStuff((dynamic)o);
        Console.WriteLine(str);
    }
}

Alternatively you can use reflection:

foreach (object o in values)
{
    Type t = o.GetType();
    if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>))
    {
        var typeParams = t.GetGenericArguments();
        var method = typeof(ContainingType).GetMethod("DoStuff").MakeGenericMethod(typeParams);
        string str = (string)method.Invoke(null, new[] { o });
    }
}

Problem

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?

Original source

Related problems