2

I am trying to set type T of a generic list via reflection. Here is my code:

if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))
{
    Type itemType = propertyType.GetGenericArguments()[0];
    var result = MyGenericMethod<itemType>(url);   
}

This is giving me a syntax error. How can set the type argument T of generic type via reflection ?

Thanks

leppie
  • 115,091
  • 17
  • 196
  • 297
Ajmal VH
  • 1,691
  • 1
  • 13
  • 27
  • ... or of [this](http://stackoverflow.com/questions/5059945/generate-generic-type-at-runtime) or [this](http://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-sharp-object-using-reflection) or [this](http://stackoverflow.com/questions/8965893/c-sharp-creating-an-unknown-generic-type-at-runtime) or [this](http://stackoverflow.com/questions/67370/dynamically-create-a-generic-type-for-template) ... this has been asked **and answered** many times before, please *do* look for duplicates *before* asking. – O. R. Mapper Apr 08 '14 at 15:39

2 Answers2

1

You can use reflection to do this by utilizing Invoke and MakeGenericMethod.

You will need to know the name of the class it is executing in, lets call it ClassName. The binding flags are also very important, if they are incorrect (guessing here since you don't show a method signature) then the MethodInfo will be null and you will get an exception.

if(/*noted conditions in question*/)
{
   Type itemType = propertyType.GetGenericArguments()[0];
   Type ThisClass = typeof(ClassName);
   MethodInfo mi = ThisClass.GetMethod("MyGenericMethod", BindingFlags.Instance | BindingFlags.NonPublic);
   MethodInfo miConstructed = mi.MakeGenericMethod(itemType);
   object[] args = { url };
   var result = miConstructed.Invoke(this, args);
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
1

Quick and dirty example:

class Program {
    static void Main( string[ ] args ) {
        Printer instance = new Printer( );
        Type type = typeof( string );

        typeof( Printer ).GetMethod( "print" )
            .MakeGenericMethod( type )             // <-- Here
            .Invoke( instance, new object[ ] { "Hello World!" } );
    }
}

class Printer {
    public void Print<T>( T t ) {
        Console.WriteLine( t.ToString( ) );
    }
}

You get the method with reflection, as usual, then add the generic parameter(s) and invoke it.

BlackBear
  • 22,411
  • 10
  • 48
  • 86