A more elegant way to dynamically get generic Action<> type by parameter count?

c#, reflection

Solution

EDIT:

BTW, Do you know of `Expression.GetActionType`?

Creates a Type object that represents a generic System.Action delegate type that has specific type arguments.

Using that method, you could do:

dType = Expression.GetActionType( parms.Select(p => p.ParameterType).ToArray() );

Other ways:

var parms = meth.GetParameters();

int numArgs = parms.Length;

if(numArgs == 0)
{
    dType = typeof(Action);
}    
else 
{
   var rawType = Type.GetType("System.Action`" + numArgs);
   dType = rawType.MakeGenericType(parms.Select(p => p.ParameterType).ToArray());
}

But there's really nothing wrong with your approach really; being as explicit as possibile is often a better choice when it comes to reflection.

Also, here's another fancy way of building your map:

typeof(Action).Assembly
              .GetExportedTypes()
              .Where(type => type.FullName.StartsWith("System.Action") 
                                  && type.IsSubclassOf(typeof(Delegate)))
              .ToDictionary(type => type.GetGenericArguments().Length)

Problem

At the moment I'm doing this (//edit: which is totally stupid as there's array which consequentily numbers its items in the same way that I did my Dictionary yesterday): ``` Dictionary<int, Type> genericMap = new Dictionary<int, Type> { { 0, typeof(Action) }, { 1, typeof(Action<>) }, { 2, typeof(Action<,>) }, { 3, typeof(Action<,,>) }, { 4, typeof(Action<,,,>) }, { 5, typeof(Action<,,,,>) }, { 6, typeof(Action<,,,,,>) }, { 7, typeof(Action<,,,,,,>) }, { 8, typeof(Action<,,,,,,,>) }, }; ``` And somewhere else... ``` var parms = meth.GetParameters(); dType = genericMap[parms.Length].MakeGenericType(parms.Select(p => p.ParameterType).ToArray()); ``` where meth is a MethodInfo. Is there a more elegant way to do that? Or do I have to define a map like this to get the correct Action<> type dynamically that corresponds to the parameter count?

Original source