1

I have a Dictionary where the keys are the name of a type and the values are objects of that type, like so:

var dict = new Dictionary<string, object>()
{
   { "System.Int32", 3 },
   { "System.String", "objectID" },
   { "System.Boolean", false }
}

I would like to iterate through that dictionary and pass the values to a generic method, like so:

static void ProcessValue<T>(T inputValue)
{
   // do something here
}

I know for each entry in the dictionary what T should be, and I know that I can get the type of T from the dictionary keys using Type.GetType(string), but I can't figure out if there is a way to pass that along to the generic method without doing something like:

foreach (var entry in dictionaryEntries)
{
    var t = Type.GetType(entry.Key);

    if (t == typeof(int))
         ProcessValue<int>(entry.Value);    
    else if (t == typeof(Guid))
         ProcessValue<Guid>(entry.Value);
    else if...
}

Is there a better way to accomplish what I'm trying to do?

Brian Campbell
  • 161
  • 1
  • 12

1 Answers1

0

You can use MakeGenericMethod call on your ProcessValue

var dict = new Dictionary<string, object>
{
    {"System.Int32", 3},
    {"System.String", "objectID"},
    {"System.Boolean", false}
};

var processValueMethod = typeof(/* type that contains ProcessValue */)
    .GetMethod("ProcessValue");

foreach (var entry in dict)
{
    var t = Type.GetType(entry.Key);
    MethodInfo method = processValueMethod.MakeGenericMethod(t);
    method.Invoke(null, new []{entry.Value});
}

See a demo

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37