Why won't this static variable increment when using generics?
Each different T
creates a new class for A<T>
and hence distinct static counters.
To get around this you can use inheritance like so:
abstract class A
{
protected static int counter;
}
class A<T> : A
{
private static int Counter {
get {
Increment();
return counter;
}
}
private static void Increment() {
counter++;
}
public int Index;
public A()
{
this.Index = Counter;
Console.WriteLine(this.Index);
}
}
Not a bug - this is by design, and is a consequence of how generics work.
A generic type like your A<T>
serves as a template - when you use type parameters, the compiler generates an actual class with that type T
, and a different one will be created for each different type T
.
This explains the results you see - there is a static field for the A<int>
and another one for the A<string>
.
This is because different types are generated under the hood for classes with different generic type parameters. This difference is only for the value type parameters as kindly noted by Ben in comment.
Check out these MSDN articles:
- Generics in the Run Time
- Reflection and Generic types
EDIT:
Consider following code:
public abstract class GenericBase<T>
{
public static int Counter { get; set; }
}
public class GenericInt : GenericBase<int>
{
}
public class GenericLong : GenericBase<long>
{
}
public class GenericDecimal : GenericBase<decimal>
{
}
[TestFixture]
public class GenericsTests
{
[Test]
public void StaticContextValueTypeTest()
{
GenericDecimal.Counter = 10;
GenericInt.Counter = 1;
GenericLong.Counter = 100;
// !! At this point value of the Counter property
// in all three types will be different - so does not shared across
// all types
}
}