Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static fields in a base class and derived classes

Tags:

scope

c#

static

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)?

like image 566
Xaqron Avatar asked May 01 '11 21:05

Xaqron


People also ask

Can static class be derived?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.

Do derived classes inherit static members?

static member functions act the same as non-static member functions: They inherit into the derived class.

Are static members inherited to subclasses in C++?

Quick A: Yes, and there are no ambiguity with static members.

What is the base class and derived class relationship?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.


2 Answers

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>.

like image 69
Marc Gravell Avatar answered Sep 18 '22 22:09

Marc Gravell


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;     } } 
like image 31
C-F Avatar answered Sep 21 '22 22:09

C-F