views:

843

answers:

4

How do you go about creating an instance of an object when given the class name as a string in an ASP.NET v2 application? For example, I've got a class called SystemLog defined in the app_code section of the application. The class is defined within the Reports namespace. To create an instance of the object, I do something like this:

Dim MyObject As New Global.Reports.SystemLog

However, I want to create this object using a string to define the type. The type name is stored in a SQL database as a string. I thinks it's probably something to do with Activator.CreateInstance(AssemblyName, TypeName) but what I don't know is what to pass in those strings. What is the assembly name of an ASP.NET web app?

Help!

Thanks, Rob.

PS. I don't want a hard coded Select statement :-)

+4  A: 
string typeName = "Your Type Name Here";
Type t = Type.GetType(typeName);
object o = Activator.CreateInstance(t);

This will give you an instanciated type. If will be up to you to cast it to the correct type and call your appropriate methods.

If you need to create a type that doesn't have a parameterless constructor there is an overload on CreateInstance that takes a params of objects to pass to a constructor. More info at this MSDN article.

Ray Booysen
A: 

Thanks - that worked but only by luck in that the object being created is in the same assembly as the Activator.CreateInstance call. If I was attempting to create it from outside the same assembly, I expect it would get a lot harder!

Cheers, Rob.

Rob Nicholson
If the assembly is in the bin folder and not strongly named you'd just need to specify the Type and Assembly name in the string. If the assembly is in the GAC, you'll also need to supply the public key and language preferences.
Zhaph - Ben Duguid
A: 

You can use this to get it from a particular assembly:

Assembly assembly = Assembly.Load("myAssembly");

Type ObjectType = assembly.GetType("Type name here");

then.....object o = Activator.CreateInstance(ObjectType);

Jobo
A: 

The following is able to create type, even if it's from another assembly:

public object CreateInstance(string typeName) {
   var type = AppDomain.CurrentDomain.GetAssemblies()
              .SelectMany(a => a.GetTypes())
              .FirstOrDefault(t => t.FullName == typeName);

   return type.CreateInstance();
}
Borka