C# Create Instance of a Class from string

In C# You can create instance of any class dynamically using Activator.CreateInstance method


public object GetInstance(string FullyQualifiedNameOfClass)
{         
     Type t = Type.GetType(FullyQualifiedNameOfClass); 
     return  Activator.CreateInstance(t);         
}

If FullyQualifiedNameOfClass is in another assembly then loop through all assemblies and find the Type. For that use below code:


public object GetInstance(string FullyQualifiedNameOfClass)
{
     Type type = Type.GetType(FullyQualifiedNameOfClass);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

If you want to return an interface type then use following code:


public ISomeInterface GetInstance(string FullyQualifiedNameOfClass)
{
     Type type = Type.GetType(FullyQualifiedNameOfClass);
     if (type != null)
         return (ISomeInterface)Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return (ISomeInterface)Activator.CreateInstance(type);
     }
     return null;
 }

Leave a Reply

Your email address will not be published.