Dynamically create an object of


I have a table in my database that I use to manage relationships across my application. it's pretty basic in it's nature - parentType,parentId, childType, childId... all as ints. I've done this setup before, but I did it with a switch/case setup when I had 6 different tables I was trying to link. Now I have 30 tables that I'm trying to do this with and I would like to be able to do this without having to write 30 case entries in my switch command.

Is there a way that I can make reference to a .Net class using a string? I know this isn't valid (because I've tried several variations of this):

Type t = Type.GetType("WebCore.Models.Page");
object page = new t();

I know how to get the Type of an object, but how do I use that on the fly to create a new object?

2/23/2009 5:20:38 PM

Accepted Answer

This link should help:


Activator.CreateInstance will create an instance of the specified type.

you could wrap that in a generic method like this:

public T GetInstance<T>(string type)
    return (T)Activator.CreateInstance(Type.GetType(type));
2/23/2009 5:22:26 PM

If the type is known by the caller, there's a better, faster way than using Activator.CreateInstance: you can instead use a generic constraint on the method that specifies it has a default parameterless constructor.

Doing it this way is type-safe and doesn't require reflection.

T CreateType<T>() where T : new()
   return new T();

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow