C#: Determine derived object type from a base class static method

Steve Hawkins picture Steve Hawkins · Nov 18, 2008 · Viewed 10.3k times · Source

In a C# program, I have an abstract base class with a static "Create" method. The Create method is used to create an instance of the class and store it locally for later use. Since the base class is abstract, implementation objects will always derive from it.

I want to be able to derive an object from the base class, call the static Create method (implemented once in the base class) through the derived class, and create an instance of the derived object.

Are there any facilities within the C# language that will allow me to pull this off. My current fallback position is to pass an instance of the derived class as one of the arguments to the Create function, i.e.:

objDerived.Create(new objDerived(), "Arg1", "Arg2");

Answer

chilltemp picture chilltemp · Nov 18, 2008

Try using generics:

public static BaseClass Create<T>() where T : BaseClass, new()
{
    T newVar = new T();
    // Do something with newVar
    return T;
}

Sample use:

DerivedClass d = BaseClass.Create<DerivedClass>();