13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

86 CHAPTER 3 Parameterized typ<strong>in</strong>g with genericsunder the covers—although we won’t be go<strong>in</strong>g so deep that you need a flashlight.We’ll have a look at what happens when you enumerate a generic collection us<strong>in</strong>gforeach <strong>in</strong> <strong>C#</strong> 2, and round off the section by see<strong>in</strong>g how reflection <strong>in</strong> the .NETFramework is affected by generics.3.4.1 Static fields and static constructorsJust as <strong>in</strong>stance fields belong to an <strong>in</strong>stance, static fields belong to the type they’redeclared <strong>in</strong>. That is, if you declare a static field x <strong>in</strong> class SomeClass, there’s exactlyone SomeClass.x field, no matter how many <strong>in</strong>stances of SomeClass you create, andno matter how many types derive from SomeClass. 7 That’s the familiar scenario from<strong>C#</strong> 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 tosee with an example. List<strong>in</strong>g 3.7 creates a generic type <strong>in</strong>clud<strong>in</strong>g a static field. We setthe field’s value for different closed types, and then pr<strong>in</strong>t out the values to show thatthey are separate.List<strong>in</strong>g 3.7Proof that different closed types have different static fieldsclass TypeWithField{public static str<strong>in</strong>g field;public static void Pr<strong>in</strong>tField(){Console.WriteL<strong>in</strong>e(field+": "+typeof(T).Name);}}...TypeWithField.field = "First";TypeWithField.field = "Second";TypeWithField.field = "Third";TypeWithField.Pr<strong>in</strong>tField();TypeWithField.Pr<strong>in</strong>tField();TypeWithField.Pr<strong>in</strong>tField();We set the value of each field to a different value, and pr<strong>in</strong>t out each field along withthe name of the type argument used for that closed type. Here’s the output from list<strong>in</strong>g3.7:First: Int32Second: Str<strong>in</strong>gThird: DateTimeSo the basic rule is “one static field per closed type.” The same applies for static <strong>in</strong>itializersand static constructors. However, it’s possible to have one generic type nested7Well, one per application doma<strong>in</strong>. For the purposes of this section, we’ll assume we’re only deal<strong>in</strong>g with oneapplication doma<strong>in</strong>. The concepts for different application doma<strong>in</strong>s work the same with generics as with nongenerictypes.Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!