Search code examples
c#classtype-conversioninstantiationconverters

How to instantiate a class based on a variable type of the class to be instantiated


Is there a way to do instantiate a class, but not by it's classname, but using the Class' type? Possibly/probably using Convert or reflection.?

e.g. I have a class and typically create an instance of it as per..

TCustDataDetailModel newDataDetail = new TCustDataDetailModel ();

but I want to be able to do it like ..

public void MyFunction (Type somePassedinParamType)
{
    somePassedinParamType newDataDetail  = new somePassedinParamType();

}

thx


Solution

  • You need to use the Activator class.

    public void MyFunction (Type somePassedinParamType)
    {
        var newInstance = Activator.CreateInstance(somePassedinParamType);    
    }
    

    Note that is you do not have an empty constructor you will need to use one of the override of CreateInstance and pass what the class needs.