I have an abstract class
abstract class ClassA
{
}
and some inheriting, non-abstract classes
class ClassB : ClassA
{
}
class ClassC : ClassA
{
}
For all inheriting classes I want to have a static field called "Instance" which is an instance of the class, created by the parameterless constructor. One way of defining that is this:
class ClassB : ClassA
{
public static ClassA Instance = new ClassB();
}
class ClassC : ClassA
{
public static ClassA Instance = new ClassC();
}
But in order to minimize redundancy, I want to define this field inside ClassA
. How do I do that? Is there some construct like below (pseudocode)?
abstract class ClassA
{
public static readonly ClassA Instance = CallConstructorOfActualClass();
}
Why I need this: Because I want to simulate abstract static getters. For each class I want to store some number which should behave statically (=no class instance needed), but different per class (e.g. ClassB
has 2, ClassC
has 5). Since that does not work, I would make an abstract (nonstatic) getter in ClassA
and always have a static Instance
field for any inheriting (non-abstract) class from which I can call that getter.