Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
like image 983
Steve Hawkins Avatar asked Nov 18 '08 21:11

Steve Hawkins


2 Answers

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>();
like image 92
chilltemp Avatar answered Nov 15 '22 12:11

chilltemp


Summary

There are two main options. The nicer and newer one is to use generics, the other is to use reflection. I'm providing both in case you need to develop a solution that works prior to .NET 2.0.

Generics

abstract class BaseClass
{
  public static BaseClass Create<T>() where T : BaseClass, new()
  {
    return new T();
  }
}

Where the usage would be:

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

Reflection

abstract class BaseClass
{
  public static BaseClass Create(Type derivedType)
  {
    // Cast will throw at runtime if the created class
    // doesn't derive from BaseClass.
    return (BaseClass)Activator.CreateInstance(derivedType);
  }
}

Where the usage would be (split over two lines for readability):

DerivedClass derivedClass
    = (DerivedClass)BaseClass.Create(typeof(DerivedClass));
like image 38
Jeff Yates Avatar answered Nov 15 '22 12:11

Jeff Yates