I've stumbled into something weird that I can't figure out if it's a bug or a feature.

I have a generic base class with a static data member.
Then, I have two classes deriving from it, using different generic types.

The weird thing is that the static data member is no longer shared between these classes, that is it has the same value for all instances of the first deriving class, but a different value for the second.
The really weird thing is that the value is different even in the BASE calss !
(value depends on the derived class).

I assume it is because the different generic types dictate a different variation of the base class, and thus these are actually two different base classes.
But this makes no sense to me.

Any ideas
is this a bug or a normal behaviour
And if it's normal, how am I supposed to have a static member between these classes


Re: Common Language Runtime Static, Generics and Inheritance


This is normal. Generics generate distinct class types. Consider this sample code:

using System;

public class Sample<T> {
public static int Static;

public class Test {
public static void Run() {
Sample<int> o1 = new Sample<int>();
Sample<short> o2 = new Sample<short>();
//o1.Static = 1; // Error CS0176
Sample<int>.Static = 1;

Just move the static variable out of the generic class into a static helper class.

Re: Common Language Runtime Static, Generics and Inheritance


Thanks for the answer.

It makes sense, but it's a hard thing to notice before you start getting weird bugs.