5

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 a couple of instances of it with different parameter instantiations, like

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

Is there a way that the instances a, b, and c share the static field counter ?

Any answers and comments are pretty much appreciated :)

marc wellman
  • 5,808
  • 5
  • 32
  • 59
  • 4
    No, but you can inherit from a non-static base class and declare the static as "protected". Also, I'm pretty sure this is duplicate question, but I can't find any others like it just now, so +1 for a good, well-posed question. – Cameron Jun 11 '12 at 18:30
  • I have forgotten to mention that I am already inheriting from a generic class what makes my attempt a bit harder I guess ... – marc wellman Jun 11 '12 at 18:32

3 Answers3

5

You could wrap the counter in it's own singleton class, then reference the counter class from A, B, and C.

Tom Studee
  • 10,316
  • 4
  • 38
  • 42
  • THAT'S IT! :) What an elegant and obvious solution. I don't think that one can make it better ... Thank you so much for saving my day :) – marc wellman Jun 11 '12 at 18:34
1

Static fields are dependent upon their class (this is how C# handles telling which static members are which), and when you pass in a different generic type you're effectively defining a separate class.

So, no. Something like a shared counter would probably be better handled by whatever class is calling the Thing That Counts, since it's that's class that'll be most interested in the state of that counter anyway. If you can't do this for whatever reason (this class is being referenced by a bunch of unrelated threads), then you can make a static class to hold the state of the library, but this causes problems with testability so I'd try to avoid it if you can.

tmesser
  • 7,558
  • 2
  • 26
  • 38
1

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++;
    }
}

The first call to GetCounterAndAddOne sets counter to 0, the second call sets counter 1, and it will go on as needed.

Protiguous
  • 89
  • 2
  • 9
YavgenyP
  • 2,113
  • 14
  • 11