Summary
There are two main options. More enjoyable and new is the use of generics, while the other is the use of reflection. I provide both options if you need to develop a solution that works before .NET 2.0.
Generics
abstract class BaseClass
{
public static BaseClass Create<T>() where T : BaseClass, new()
{
return new T();
}
}
Where to be used:
DerivedClass derivedInstance = BaseClass.Create<DerivedClass>();
Reflection
abstract class BaseClass
{
public static BaseClass Create(Type derivedType)
{
return (BaseClass)Activator.CreateInstance(derivedType);
}
}
If there will be a use (division into two lines for readability):
DerivedClass derivedClass
= (DerivedClass)BaseClass.Create(typeof(DerivedClass));
source
share