Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an instance of a class in an ASP.NET application

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 :-)

like image 497
Rob Nicholson Avatar asked Jan 07 '09 23:01

Rob Nicholson


2 Answers

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.

like image 148
Ray Booysen Avatar answered Sep 28 '22 02:09

Ray Booysen


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();
}
like image 45
Borka Avatar answered Sep 28 '22 03:09

Borka