Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Generics with many types

Tags:

c#

generics

I have a chunk of code where sometimes I need to create a new generic type, but with an unknown number of generic parameters. For example:

public object MakeGenericAction(Type[] types)
{
  return typeof(Action<>).MakeGenericType(paramTypes);
}

The problem is that if I have more than one Type in my array, then the program will crash. In the short term I have come up with something like this as a stop-gap.

public object MakeGenericAction(Type[] types)
{
  if (types.Length == 1)
  {
    return typeof(Action<>).MakeGenericType(paramTypes);
  }
  else if (types.Length ==2)
  {
    return typeof(Action<,>).MakeGenericType(paramTypes);
  }
  ..... And so on....
}

This does work, and is easy enough to cover my scenarios, but it seems really hacky. Is there a better way to handle this?

like image 909
A.R. Avatar asked Jun 07 '11 17:06

A.R.


1 Answers

In that case, yes:

Type actionType = Expression.GetActionType(types);

The problem here though is that you will probably be using DynamicInvoke which is slow.

An Action<object[]> then access by index may outperform an Action<...> invoked with DynamicInvoke

like image 159
Marc Gravell Avatar answered Oct 06 '22 11:10

Marc Gravell