2

I have a problem regarding creating a object of a class in c# where a class name is stored in a string variable

eg. String str="Pilot"

As we create object of the class like this
ClassName objectname=new ClassName();

due to some reason instead of ClassName i need to use String Variable which stores my Class name.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • 1
    have a look at this question: [How do I create an instance from a string in C#?](http://stackoverflow.com/questions/648160/how-do-i-create-an-instance-from-a-string-in-c) –  Mar 01 '13 at 18:42
  • @Usre...what is the reason for this requirement? – MikeTWebb Mar 01 '13 at 18:43

4 Answers4

2

You would use Type.GetType(string) and then Activator.CreateInstance(Type):

Type type = Type.GetType(str);
object instance = Activator.CreateInstance(type);

Note:

  • The type name must include the namespace, e.g. Foo.Bar.SomeClassName
  • Unless you specify an assembly-qualified type name, Type.GetType(string) will only look in the currently executing assembly and mscorlib. If you want to use other assemblies, either use an assembly-qualified name or use Assembly.GetType(string) instead.
  • This assumes there's a public parameterless constructor for the type
  • Your variable type has to just be instance, as the type of a variable is part of what's needed at compile time
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Here is an example. You will probably need to specify the full namespace path.

Namespace.Pilot config = (Namespace.Pilot)Activator.CreateInstance(Type.GetType("Namespace.Pilot"));
Adam Plocher
  • 13,994
  • 6
  • 46
  • 79
0

You would use Reflection to do so:

var type = Assembly.Load("MyAssembly").GetTypes().Where(t => t.Name.Equals(str));
return Activator.CreateInstance(type);
Corey Adler
  • 15,897
  • 18
  • 66
  • 80
0

You can do this via usage of the Activator:

var type = "System.String";
var reallyAString = Activator.CreateInstance(
        // need a Type here, so get it by type name
        Type.GetType(type), 
        // string's has no parameterless ctor, so use the char array one
        new char[]{'a','b','c'});
Console.WriteLine(reallyAString);
Console.WriteLine(reallyAString.GetType().Name);

Output:

abc
String
JerKimball
  • 16,584
  • 3
  • 43
  • 55