Dynamically Create Instance of a Class at Runtime in C#

Introduction

Normally we create an instance/object of a class using the name of the class, for example if I have a class named User in my application, normally we create that class using the name like the following.
  1. User UR = new User();  
  2. UR.ID = 1;  
  3. UR.Name = "Kailash";  
But if someone tells you to create an instance of a classes you are using in your application at runtime or by passing a string as the class name, how will you do that? Don't worry, the Microsoft .Net Framework provides a solution for this. The Assembly class in the System.Reflection namespace and the Activator class in the System namesspace helps to create an instance of the class at run time. The following explains the Assembly and Activation classes.
 
Assembly 
 
The Mycrosoft .Net Framework provides the Assembly class for getting the details or for reading about your application's assembly. (It represents an assembly that is a reusable, versionable and self-describing building block of a Common Language Runtime application.) For more details about the Assembly class visit this site.

Activatior

This class contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited. For More Details Visit this site.
 
Getting Started
 
Create a console project in Visual Studio and provide the name of the project as you like, press the OK Button. You will get your first class with a Main method. Add the reference for the System.Reflection namespace as in the following:
  1. namespace DynamicCreateInstanceofclass  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.         }  
  8.     }  
  9. }  
Declare a class with the name "User" in the same namespace with the following properties. 
  1. public class User    
  2. {    
  3.     public int ID { getset; }    
  4.     public string Name { getset; }    
  5. }    
Declare a namespace with the name "IUser" and declare the method in this namespace with the name GetUserDetails. This function will return a User class or the return type of this function is a User class. 
  1. interface IUser    
  2. {    
  3.     User GetUserDetails();    
  4. }   
Declare another class with the name UserDetails that will inherit the preceding interface (IUser). Write some code in the inherited function.
  1. public class UserDetails:IUser  
  2. {  
  3.    public User GetUserDetails()  
  4.    {  
  5.        User UR = new User();  
  6.        UR.ID = 1;  
  7.        UR.Name = "Kailash";  
  8.        return UR;  
  9.    }  
  10. }  
Declare a static function with the name CreateInstance. This function will accept an interface and class name as a parameter as in the following:
  1. public static I CreateInstance<I>() where I : class  
  2. {  
  3.     string assemblyPath = Environment.CurrentDirectory + "\\DynamicCreateInstanceofclass.exe";  

  4.     Assembly assembly;  
  5.   
  6.     assembly = Assembly.LoadFrom(assemblyPath);  
  7.     Type type = assembly.GetType("DynamicCreateInstanceofclass.UserDetails");  
  8.     return Activator.CreateInstance(type) as I;  
  9. }  
In the preceding code the line number, the string variable contains your application's assembly path. Line number 5 creates an object of the assembly class. In line number 7 is the static function LoadFrom that loads the application's assembly, it takes an assembly path as a string parameter. The GetType function line number 8 of the Assembly class takes a class's full name (class name with assembly or namespace name) as parameter and returns the type of that class. In line number 9 the CreateInstance function is the static function of the activator class that takes the type of class and returns the instance of that class. 
 
Write the following code in the Main function that prints the return value of the GetUserdetails function:
  1. static void Main(string[] args)  
  2. {  
  3.    //DynamicCreateInstanceofclass  
  4.   
  5.    //   UserManager UM = new UserManager();  
  6.   
  7.    User UR= CreateInstance<IUser>().GetUserDetails();  
  8.   
  9.    Console.WriteLine("User ID:" + UR.ID);  
  10.    Console.WriteLine("User Name:" + UR.Name);  
  11.   
  12.    Console.WriteLine("Press Key to exit");  
  13.    Console.ReadLine();  
  14. }  
Full Code
  1. namespace DynamicCreateInstanceofclass  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.            //DynamicCreateInstanceofclass  
  8.   
  9.            //   UserManager UM = new UserManager();  
  10.   
  11.            User UR= CreateInstance<IUser>().GetUserDetails();  
  12.   
  13.            Console.WriteLine("User ID:" + UR.ID);  
  14.            Console.WriteLine("User Name:" + UR.Name);  
  15.   
  16.            Console.WriteLine("Press Key to exit");  
  17.            Console.ReadLine();  
  18.         }  
  19.         public static I CreateInstance<I>() where I : class  
  20.         {  
  21.             string assemblyPath = Environment.CurrentDirectory + "\\DynamicCreateInstanceofclass.exe";  
  22.   
  23.             Assembly assembly;  
  24.   
  25.             assembly = Assembly.LoadFrom(assemblyPath);  
  26.             Type type = assembly.GetType("DynamicCreateInstanceofclass.UserDetails");  
  27.             return Activator.CreateInstance(type) as I;  
  28.         }  
  29.     }  
  30.     public class UserDetails:IUser  
  31.     {  
  32.         public User GetUserDetails()  
  33.         {  
  34.             User UR = new User();  
  35.             UR.ID = 1;  
  36.             UR.Name = "Kailash";  
  37.             return UR;  
  38.         }  
  39.     }  
  40.     public class User  
  41.     {  
  42.         public int ID { getset; }  
  43.         public string Name { getset; }  
  44.     }  
  45.     interface IUser  
  46.     {  
  47.         User GetUserDetails();  
  48.     }  
  49. }  
 
 
In this article, I hope you have gotten how to create an instance of a class at run time.


Similar Articles