Is it possible to invoke a generic static class mthod through reflection.

Hi all,

I have the following scenario. I have a generic static class. Is there a way for me to invoke something like that using reflection. For example. I have a static class with a method.

MyClass<T>.Show()

The item being shown depends on T.

Can I invoke such a method using reflection I have the string (MyClass<MyType>) given to me, but I cannot create an instance of that using reflection (since MyClass is a static class).

Any help is appreciated.

Thanks ahead.

David



Answer this question

Is it possible to invoke a generic static class mthod through reflection.

  • Imanol

    Hi David.

    You can simply pass the generic type specifier to the typeof() call, then call InvokeMember as normal on the returned type, thusly:

    using System;

    using System.Collections.Generic;

    namespace ConsoleApplication1

    {

    class Program

    {

    static void Main(string[] args)

    {

    try

    {

    Type type = typeof(MyClass<int>);

    type.InvokeMember("PrintType", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public, null, null, null);

    }

    catch(Exception ex)

    {

    Console.Error.WriteLine(ex.ToString());

    }

    Console.ReadLine();

    }

    }

    public class MyClass<T>

    {

    public static void PrintType()

    {

    Console.WriteLine(typeof(T).FullName);

    }

    }

    }



  • cstrader

    Yes, you've got it. And yes, you need the 1, although to be honest I'm not sure why. I think it might be the indexer of the generic type parameter



  • A.Russell

    Hi Mark

    Thanks for the response. In regards to your addendum, I just want to make sure I understand that correctly.

    ConsoleApplication1.MyClass - this portion is my actual static class

    '1 - the ' is the backtick, but does the 1 need to be there

    [System.String] - this portion is where I will put my actual type T.

    Is my understanding correct Thanks again for your help.

    David


  • Edouard Mercier

    Addendum:

    To get a generic type when you've only got the string type name, you need to use the backtick operator in the string passed to GetType. In the above code, you'd use:

    Type type = Type.GetType("ConsoleApplication1.MyClass`1[System.String]", true);



  • Is it possible to invoke a generic static class mthod through reflection.