Static fields in a base class and derived classes

C#StaticScope

C# Problem Overview


In an abstract base class if we have some static fields then what happens to them ?

Is their scope the classes which inherit from this base class or just the type from which it is inheriting (each subclass has it's own copy of the static field from the abstract base class)?

C# Solutions


Solution 1 - C#

static members are entirely specific to the declaring class; subclasses do not get separate copies. The only exception here is generics; if an open generic type declares static fields, the field is specific to that exact combination of type arguments that make up the closed generic type; i.e. Foo<int> would have separate static fields to Foo<string>, assuming the fields are defined on Foo<T>.

Solution 2 - C#

As pointed out in other answer, the base class static field will be shared between all the subclasses. If you need a separate copy for each final subclass, you can use a static dictionary with a subclass name as a key:

class Base
{
    private static Dictionary<string, int> myStaticFieldDict = new Dictionary<string, int>();

    public int MyStaticField
    {
        get
        {
            return myStaticFieldDict.ContainsKey(this.GetType().Name)
                   ? myStaticFieldDict[this.GetType().Name]
                   : default(int);
        }

        set
        {
            myStaticFieldDict[this.GetType().Name] = value;
        }
    }

    void MyMethod()
    {
        MyStaticField = 42;
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXaqronView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#C-FView Answer on Stackoverflow