C# Reflection – Dynamically Invoking Methods from Classes in an Assembly

Updated on     Kisan Patel

If you are creating a new compiler or interpreter for C# or any other .NET language, you need to use reflection to find information about objects loaded in the compiler or interpreter. You can not only find information about different objects, but also invoke methods on them dynamically, if you know the name of the method you want to call and the arguments you want to pass to the method.

In addition to transferring information into a method, C# allows you to return information from a method to the calling function.

using System;
using System.Reflection;

namespace DynamicInvoke
{
    class Program
    {

        public static void DoDynamicInvoke(Assembly a)
        {
            foreach (Type t in a.GetTypes())
            {
                if (t.IsClass == false)
                    continue;
                
                if (t.GetInterface("IMyInterface") == null)
                    continue;

                //Creating instance of class
                object obj = Activator.CreateInstance(t);
                object[] args = { 10, 30 };
                object result;

                try
                {
                    //Invoking method sum() dynamically
                    result = t.InvokeMember("sum",
                                            BindingFlags.Default | BindingFlags.InvokeMethod,
                                            null, obj, args);
                    Console.WriteLine("Result of dynamic call : {0}", result);

                    //Call an Interface method
                    object[] args2 = { };

                    //Invoking method printHelloWorld() dunamically
                    t.InvokeMember("printHelloWorld",
                                    BindingFlags.Default | BindingFlags.InvokeMethod,
                                    null, obj, args2);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: {0}", e);
                }
            }
        }

        static void Main(string[] args)
        {
            Assembly a = Assembly.GetCallingAssembly();
            DoDynamicInvoke(a);
        }
    }

    interface IMyInterface
    {
        void printHelloWorld();
    }

    public class DoMyInterface : IMyInterface
    {
        public int sum(int a, int b)
        {
            return a + b;
        }

        public void printHelloWorld()
        {
            Console.WriteLine("Hello World!");
        }
    }

}

the above code will produce below output…

reflection-InvokeMethod-example

Here, Type.InvokeMember invokes the specified member, using the specified binding constraints and matching the specified argument list.


C#

Leave a Reply