S
S
Slavik Sharov2015-09-22 08:59:35
C++ / C#
Slavik Sharov, 2015-09-22 08:59:35

C# how to instantiate a class by name in string?

There are several classes, the class name is specified in string, how can I create an instance of the class by this name?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
heartdevil, 2015-09-22
@spark36

Hello.
Here is a good example .
Here's more from msdn .

A
ar4ebaldello, 2015-09-22
@ar4ebaldello

var classes = new[]
{
    new
    {
        Name = "System.String",
        AssemblyName = "mscorlib",
        Args = new object[] { "Single argument".ToCharArray() }
    },
    new
    {
        Name = "Newtonsoft.Json.Linq.JObject",
        AssemblyName = "Newtonsoft.Json",
        Args = new object[] {}
    },
    new
    {
        Name = "System.IO.FileInfo",
        AssemblyName = "mscorlib",
        Args = new object[] { @"C:\Windows\System32\cmd.exe" }
    }
};
            
var instances = classes
    .Select(i =>
    {
        var assembly = Assembly.Load(i.AssemblyName);
        var type = assembly.GetType(i.Name);
        var instance = Activator.CreateInstance(type, i.Args);

        return instance;
    })
    .ToArray();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question