Dynamically create an object of <Type>

thaBadDawg picture thaBadDawg · Feb 23, 2009 · Viewed 92k times · Source

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?

Answer

Jason Miesionczek picture Jason Miesionczek · Feb 23, 2009

This link should help:
https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance

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));
}