Search code examples
c#inheritancestatic-variables

Making a superclass have a static variable that's different for each subclass in c#


Without any code in the subclasses, I'd like an abstract class to have a different copy of a static variable for each subclass. In C#

abstract class ClassA
{
    static string theValue;

    // just to demonstrate
    public string GetValue()
    {
        return theValue;
    }
    ...
}
class ClassB : ClassA { }
class ClassC : ClassA { }

and (for example):

(new ClassB()).GetValue(); // returns "Banana"
(new ClassC()).GetValue(); // returns "Coconut"

My current solution is this:

abstract class ClassA
{
    static Dictionary<Type, string> theValue;
    public string GetValue()
    {
        return theValue[this.GetType()];
    }
    ...
}

While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?

This is similar to Can I have different copies of a static variable for each different type of inheriting class, but I have no control over the subclasses


Solution

  • While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?

    There isn't really a built-in way of doing this, as you're kind of violating basic OO principles here. Your base class should have no knowledge of subclasses in traditional object oriented theory.

    That being said, if you must do this, your implementation is probably about as good as you're going to get, unless you can add some other info to the subclasses directly. If you need to control this, and you can't change subclasses, this will probably be your best approach.