Prev | Current Page 179 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

x field, no matter how many instances of SomeClass you create, and
no matter how many types derive from SomeClass.7 That??™s the familiar scenario from
C# 1??”so how does it map across to generics?
The answer is that each closed type has its own set of static fields. This is easiest to
see with an example. Listing 3.7 creates a generic type including a static field. We set
the field??™s value for different closed types, and then print out the values to show that
they are separate.
class TypeWithField
{
public static string field;
public static void PrintField()
{
Console.WriteLine(field+": "+typeof(T).Name);
}
}
...
TypeWithField.field = "First";
TypeWithField.field = "Second";
TypeWithField.field = "Third";
TypeWithField.PrintField();
TypeWithField.PrintField();
TypeWithField.PrintField();
We set the value of each field to a different value, and print out each field along with
the name of the type argument used for that closed type. Here??™s the output from listing
3.7:
First: Int32
Second: String
Third: DateTime
So the basic rule is ???one static field per closed type.??? The same applies for static initializers
and static constructors. However, it??™s possible to have one generic type nested
7 Well, one per application domain. For the purposes of this section, we??™ll assume we??™re only dealing with one
application domain.


Pages:
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191