Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 257
ste Avatar asked Dec 03 '09 21:12

ste


1 Answers

There is a more elegant way. You can exploit the fact that statics in a generic base class are different for each derived class of a different type

public abstract class BaseClass<T> where T : class
{
    public static int x = 6;
    public int MyProperty { get => x; set => x = value; }
}

For each child class, the static int x will be unique for each unique T Lets derive two child classes, and we use the name of the child class as the generic T in the base class.

public class ChildA: BaseClass<ChildA>
{
}

public class ChildB : BaseClass<ChildB>
{
}

Now the static MyProperty is unique for both ChildA and ChildB

var TA = new ChildA();
TA.MyProperty = 8;
var TB = new ChildB();
TB.MyProperty = 4;
like image 133
JimbobTheSailor Avatar answered Oct 04 '22 03:10

JimbobTheSailor