Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic 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 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 :)

like image 519
marc wellman Avatar asked Jun 11 '12 18:06

marc wellman


3 Answers

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

like image 108
Tom Studee Avatar answered Oct 26 '22 23:10

Tom Studee


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.

like image 27
tmesser Avatar answered Oct 26 '22 23:10

tmesser


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.

like image 27
YavgenyP Avatar answered Oct 26 '22 22:10

YavgenyP