Wednesday, May 30, 2012

MakeGenericType

When does the following line of code could fail with "The number of generic arguments provided doesn't equal the arity of the generic type definition"?


var t = typeof (SomeGenericClass<,,>).MakeGenericType (typeof (int), typeof (int), typeof (int));

Where SomeGenericClass is defined as:

public class SomeGenericClass<TT1T2>
{
}

Answer (thx for Elena):

If SomeGenericClass is defined inside another generic type, its generic types arguments will consist of root type generic arguments and its own generic arguments. MakeGenricType will cut of all generic type arguments, so you have to provide types for base type definition too:


public class SomeRootClass<T3>
{
  public class SomeGenericClass<TT1T2>
  {
  }
...

var t = typeof (SomeGenericClass<,,>).MakeGenericType (typeof (T3), typeof (int), typeof (int), typeof (int));
...
}

2 comments:

  1. public class SomeGenericClass1<U>
    {
    public class SomeGenericClass<T, T1, T2>
    {
    }

    public void MakeSome()
    {
    var t = typeof (SomeGenericClass&<,,>).MakeGenericType (typeof (int), typeof (int), typeof (int));
    }
    }


    void Main()
    {
    var u = new SomeGenericClass1<string>();
    u.MakeSome();
    }

    ReplyDelete