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 :)
You could wrap the counter in it's own singleton class, then reference the counter class from A, B, and C.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With