How to Create an Instance from a String in C#

Create an instance of a class from a string

Take a look at the Activator.CreateInstance method.

C# Instantiate a Class from String name

This technical called Reflection, that means call an instance from string.
My calling class will be

public class Class1
{
public string Property { get; set; } = "I'm class1";
public void DoSpecialThings()
{
Console.WriteLine("Class1 does special things");
}
}

Next I create an instance in a static function, should put your all classes in a same namespace to easy control

    public static dynamic GetClassFromString(string className)
{
var classAddress = $"NetCoreScripts.{className}";
Type type = GetType(classAddress);

// Check whether the class is existed?
if (type == null)
return null;

// Then create an instance
object instance = Activator.CreateInstance(type);

return instance;
}

And a GetType method

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

I use dynamic type to implement quickly, basically you can use interface for explicit coding.

    static async Task Main(string[] args)
{
dynamic instance = GetClassFromString("Class1");

Console.WriteLine(instance.GetType().FullName); //NetCoreScripts.Class1

Console.WriteLine(instance.GetType().Name); //Class1

Console.WriteLine(instance.Property); //I'm class1

instance.Property = "Class1 has been changed";
Console.WriteLine(instance.Property); //Class1 has been changed

instance.DoSpecialThings(); // Class1 does special things
}

How do I create an instance from a string in C#?

  • You need to specify the full type name to Type.GetType(), including namespace, e.g. "Company.Project2.Type"
  • If the type isn't in the same assembly (or mscorlib), you need to give the assembly name too, including version information if it's strongly typed. For example, for a non-strongly typed assembly Company.Project2.dll, you might specify "Company.Project2.Type, Company.Project2".
  • To call a constructor with parameters you can call Activator.CreateInstance(Type, Object[]) or get the exact constructor you want with Type.GetConstructor() and then call ConstructorInfo.Invoke().

If that doesn't help, please give more information.

c# create an instance of an object from string

You'll need to use CodeDom to compile an in-memory assembly, and then use reflection to create the type.

Here's a sample article on MSDN that walks through the process of code generation.

Once you've compiled the code, you can use Activator.CreateInstance to create an instance of it.

Create object instance of a class from its name in string variable

Having the class name in string is not enough to be able to create its instance.
As a matter of fact you will need full namespace including class name to create an object.

Assuming you have the following:

string className = "MyClass";
string namespaceName = "MyNamespace.MyInternalNamespace";

Than you you can create an instance of that class, the object of class MyNamespace.MyInternalNamespace.MyClass using either of the following techniques:

var myObj = Activator.CreateInstance(namespaceName, className);

or this:

var myObj = Activator.CreateInstance(Type.GetType(namespaceName + "." + className));

Hope this helps, please let me know if not.

Create instance of class and call method from string

// Find a type you want to instantiate: you need to know the assembly it's in for it, we assume that all is is one assembly for simplicity
// You should be careful, because ClassName should be full name, which means it should include all the namespaces, like "ConsoleApplication.MyClass"
// Not just "MyClass"
Type type = Assembly.GetExecutingAssembly().GetType(ClassName);
// Create an instance of the type
object instance = Activator.CreateInstance(type);
// Get MethodInfo, reflection class that is responsible for storing all relevant information about one method that type defines
MethodInfo method = type.GetMethod(MethodName);
// I've assumed that method we want to call is declared like this
// public void MyMethod() { ... }
// So we pass an instance to call it on and empty parameter list
method.Invoke(instance, new object[0]);

How do I create an instance from a string that provides the class name?

Activator.CreateInstance(Type.GetType(ClassName));

Creating an instance from a class defined by a string

You don't need reflection here - use Activator

IModel model = (IModel)Activator.CreateInstance(Type.GetType(typeName));

Creating instance by string and adding to collection

You need to provide a namespace for your classes:

string[] types = { "MyApplication.Child1", "MyApplication.Child2" };

Then, you can create an instance using the actual type:

Parent parent = Activator.CreateInstance(Type.GetType(this.types[0]));


Related Topics



Leave a reply



Submit