Static fields in generic classes
One of today's questions had to do with how static fields work in generic types in the upcoming C# 2.0. For example, what would the output be from the following code?
using System;
class Gen<T> {
public static int X = 0;
}
class Test {
static void Main() {
Console.Write(Gen<int>.X);
Console.Write(Gen<string>.X);
Gen<int>.X = 5;
Console.Write(Gen<int>.X);
Console.Write(Gen<string>.X);
}
}
The correct answer is: 0050. The details can be found in section 25.1.4 of the ECMA C# Language specification:
A static variable in a generic class declaration is shared amongst all instances of the same closed constructed type (§26.5.2), but is not shared amongst instances of different closed constructed types. These rules apply regardless of whether the type of the static variable involves any type parameters or not.
Comments
- Anonymous
August 14, 2005
Guz Perez pointed out an interesting info about how static fields are going to be implemented in the upcoming C# 2.0...