I have a set of classes which should all have a static string member. Let's call it TABLENAME. The base class ClassA<T>
, a templated class, for all of these classes has a protected static string member called TABLENAME
. Because of how dotnet handles static members for templated classes, each derived class gets its own instance of the static member. In addition, each class has it's own static constructor which sets TABLENAME
. So far so good.
The issue I'm having is twofold.
- Subclasses of
ClassA
appear to be able to accessTABLENAME
for other subclasses. i.e.ClassAB
can referenceClassAC.TABLENAME
. - Accessing
ClassAC.TABLENAME
fromClassAB
does not trigger the static constructor inClassAC
.
Are there any good patterns for giving a set of classes a set of static members where each derived class has it's own set of values, and there is no way to access these values before they have been set.
Right now I can get around the issue by adding a non-static method to the base class called Tablename()
, which returns the static string member TABLENAME
. In the cases where ClassAB
needs access to the TABLENAME
from ClassAC
, I can create an instance of ClassAC
and call Tablename()
. This will trigger the static constructor of ClassAC
. I don't like this solution because you can accidentally access ClassAC.TABLENAME
directly, which will return null, since it does not trigger static constructor for ClassAC
.
The reason I want a set of static members is that I don't want to initialize these fields more than once per derived class.
Thoughts, ideas?