Common classes and static fields

Is there a way to share one static variable between several different generic classes?

I have a class

class ClassA <T> : ObservableCollection<T> { static int counter; //... } 

and several instances of it with different instances of parameters, for example

 ClassA<int> a = new ClassA<int>(); ClassA<double> b = new ClassA<double>(); ClassA<float> c = new ClassA<float>(); 

Is there a way in which instances a, b, and c share a static field counter?

Any answers and comments are greatly appreciated :)

+4
source share
3 answers

You can wrap the counter in your own singleton class, and then reference the counter class from A, B, and C.

+4
source

Static fields depend on their class (this is how C # processes messages, what static members are), and when you pass another generic type, you effectively define a separate class.

So no. Something like a general counter is likely to be handled best by any class that calls Thing That Counts, since this class will be most interested in the state of that counter. If you cannot do this for any reason (a bunch of unrelated threads refer to this class), you can make a static class to hold the library state, but this causes problems with testability, so I would try to avoid this if you can.

+1
source

The simplest solution:

  class Program { static void Main(string[] args) { ClassA<int> a = new ClassA<int>(); ClassA<double> b = new ClassA<double>(); Console.WriteLine(a.GetCounterAndAddOne()); Console.WriteLine(b.GetCounterAndAddOne()); Console.Read(); } } class BaseA { protected static int counter = 0; } class ClassA<T>:BaseA { public int GetCounterAndAddOne() { return BaseA.counter++; } } 

firsr call GetCounterAndAddOne prints 0, second 1, and it will continue as needed

+1
source

All Articles