Sunday, July 10, 2016

How to create an instance of class dynamically and invoke method?

Normally we create instance of class using new keyword followed by class name. In below example new instance of “TestClass” is created using new keyword.

TestClass test = new TestClass();

But if you want to create an instance of class dynamically from assembly, how you can do it? You can do it using reflection by calling Activator.CreateInstance method. Activator class is part of System namespace. See below example how Activator.CreateInstance method used to create an instance of type.

namespace TestLibrary
{
    public class TestFile
    {
        public void DisplayFileName(string fileName)
        {
            Console.WriteLine("File Name :- {0}", fileName);
        }
    }
}




"TestLibrary" class library project added to console application and created above mentioned "TestFile" class and added reference of "TestLibrary" project to console application.  See below code from console application to dynamically create an instance of "TestFile" class and invoke "DisplayFileName" method.

Code -
public class Program
{
    static void Main(string[] args)
    {
        //Loads Assembly
        Assembly assembly = Assembly.Load("TestLibrary");
        //Gets type which object you wants to create
        Type t = assembly.GetType("TestLibrary.TestFile");
        //creates an instance of given type
        object obj = Activator.CreateInstance(t);
        //parameters for method
        object[] parameters = new object[] {"Binary File"};
        //Invokes method of class
        t.InvokeMember("DisplayFileName", BindingFlags.InvokeMethod, null, obj, parameters);

        Console.ReadLine();
    }
}


Output - 









In above example, an instance of “TestFile” class (of different assembly) is created and invoked “DisplayFileName” method dynamically.

First you need to load “TestLibrary” assembly using Assembly.Load method. You need to add reference of “TestLibrary” assembly in your application. If you want to load other assembly which is not referenced in your project, then you can use Assembly.LoadFile method to load external assembly. After successfully loading assembly, you need to load class using Assembly.Gettype instance method and create instance of that class using Activator.CreateInstance method. Once you get an instance of “TestFile” class, you can invoke “DisplayFileName” method via type InvokeMemeber method. The whole process is done dynamically via Reflection.

After reading this article, I hope you have more understating about how you can create an instance of class and invoke method dynamically via reflection. Please leave your feedback in comments below.

References –

See Also –

No comments:

Post a Comment