Thursday, November 29, 2012

How to: invoke C# generic method dynamically

Here is the sample code I figure out,

using System;

namespace X
{
    class Program
    {
        static void Main(string[] args)
        {
            string byString = "Today"; //or tomorow

            var GenericType = Type.GetType("X." + byString);
            var GenericIns = Activator.CreateInstance(GenericType);

            var genericMethod = typeof(Program).GetMethod("GetList")
                .MakeGenericMethod(GenericType);

            var output = genericMethod.Invoke(null, new object[] { GenericIns });


        }

        public static T GetList<T>(T input) where T : new()
        {
            Console.WriteLine("Invoked " + input);
            return input;
        }
    }

    class Today
    {
    }

    class Tomorrow
    {
    }
}

No comments:

 
Locations of visitors to this page