0

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.

Kjara
  • 2,504
  • 15
  • 42
  • Why not just have an abstract method on ClassA that returns an int, then define it in each derived class to return whatever int you want for each class? – Ian Oct 30 '18 at 15:37
  • Try this: `abstract class ClassA where TDerived : ClassA, new() { public static readonly TDerived Instance = new TDerived(); }` – Xiaoy312 Oct 30 '18 at 15:42

0 Answers0