Wednesday, August 22, 2012

Invoking function at runtime using reflection C#

using System;
using System.Reflection;

namespace InvokeFunctionAtRuntime
{

    class Program
    {
        static void Main(string[] args)
        {
            Type type1 = typeof(Calculator);

            object calculator = Activator.CreateInstance(type1);

            Object[] parameters = new Object[] { 5, 10 };

            int res = (int)type1.InvokeMember("Add", BindingFlags.InvokeMethod, null, calculator, parameters);

            Console.Write("Result: {0} \n", res);

            Console.Read();
        }
    }

    /// <summary>
    /// This method is for adding two numbers.
    /// </summary>
    class Calculator
    {
        public int Add(int n1, int n2)
        {
            return n1 + n2;
        }
    }

}
Post a Comment