0

I have to write a function with class Name as Parameter to function, which is in string. So that i need to create instance of this class name.

createInstance(string ClassName){
  .............
  //Here i Need to create instance of  ClassName,
  .............

 }
sandeep
  • 2,862
  • 9
  • 44
  • 54

3 Answers3

4
Activator.CreateInstance(Type.GetType(ClassName));
alexm
  • 6,854
  • 20
  • 24
2
Type t = Assembly.GetType(className);
Activator.CreateInstance(t);

Works only if T is a public type and has a parameterless, public constructor. But thats the pattern and it can be made to work in other cases too.

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Johannes Rudolph
  • 35,298
  • 14
  • 114
  • 172
1

As everybody told you, you have to get the type you are looking for and then pass it to the CreateInstance method of Activator in this way:

Type t = Type.GetType(className);
Activator.CreateInstance(t);

Just be careful to the fact that if you pass to GetType the fullname of the class you are trying to instantiate (e.g. "MyNamespace.Foo"), it returns you the type only if it is called from inside the same assembly as the searched class, otherwise it returns null.

If you want to have it work for types that are in a generic assembly you have to use the AssemblyQualifiedName (take a look here for the details: http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx)

Francesco Baruchelli
  • 7,320
  • 2
  • 32
  • 40