Non-Static method of Assembly in C#

In this article we will discuss about how to execute the non-static method of an Assembly through reflection in C#.
  • 3338

We can get the metadata of the methods available in the Assembly but also we can execute the non-static method of an Assembly using Reflection. To call the non-static method we need to create the object and then through the object we can call the non-static method and we know that we can't create the object directly in it. So for it we will get the constructor information and through it we will get the object and through the object we will call the non-static method and will execute it by passing the parameter if any because we know that when we create the object the constructor is automatically call and vise-versa.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

 

namespace reflection

{

    class Program

    {

        static void Main(string[] args)

        {

            Assembly asm = Assembly.LoadFrom(@"D:\meghawebsite\reflassm\reflassm\bin\Debug\reflassm.dll");

            Type[] type = asm.GetTypes();

            foreach (Type t in type)

            {

                if (t.Name == "mycls")

                {

                    MethodInfo[] minfo = t.GetMethods();

                    foreach (MethodInfo m in minfo)

                    {

                        if (m.Name == "show")

                        {

                            ConstructorInfo[] cinfo = t.GetConstructors();

                            object clsobj = cinfo[0].Invoke(null);//To invoke the constructor to return the object

                            Object[] ob = new object[] {10};// The method has only one parameter of int type.

                            m.Invoke(clsobj, ob);//Invoke method by passing two parameters one is object and another is its parameter value

                        }

                    }

                }

            }

            Console.ReadLine();

        }

    }

}

Output:

image3.jpg

In the above output it is clear that a constructor have been called and though which a object has been returned by it which in turns call the show method.

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.