15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Generics features ❘ 113<br />

}<br />

}<br />

}<br />

IEnumerator IEnumerable.GetEnumerator()<br />

{<br />

return GetEnumerator();<br />

}<br />

code snippet LinkedListSample/LinkedList.cs<br />

Using the generic LinkedList < T > , you can instantiate it with an int type, <strong>and</strong> there ’ s no boxing.<br />

Also, you get a compiler error if you don ’ t pass an int with the method AddLast() . Using the generic<br />

IEnumerable < T > , the foreach statement is also type - safe, <strong>and</strong> you get a compiler error if that variable in<br />

the foreach statement is not an int :<br />

var list2 = new LinkedList < int > ();<br />

list2.AddLast(1);<br />

list2.AddLast(3);<br />

list2.AddLast(5);<br />

foreach (int i in list2)<br />

{<br />

Console.WriteLine(i);<br />

}<br />

code snippet LinkedListSample/Program.cs<br />

Similarly, you can use the generic LinkedList < T > with a string type <strong>and</strong> pass strings to the<br />

AddLast() method:<br />

var list3 = new LinkedList < string > ();<br />

list3.AddLast("2");<br />

list3.AddLast("four");<br />

list3.AddLast("foo");<br />

foreach (string s in list3)<br />

{<br />

Console.WriteLine(s);<br />

}<br />

Every class that deals with the object type is a possible c<strong>and</strong>idate for a generic<br />

implementation. Also, if classes make use of hierarchies, generics can be very helpful in<br />

making casting unnecessary.<br />

generiCs feaTures<br />

When creating generic classes, you might need some more <strong>C#</strong> keywords. For example, it is not possible to<br />

assign null to a generic type. In this case, the keyword default can be used, as demonstrated in the next<br />

section. If the generic type does not require the features of the Object class, but you need to invoke some<br />

specifi c methods in the generic class, you can defi ne constraints.<br />

This section discusses the following topics:<br />

➤<br />

➤<br />

➤<br />

➤<br />

D e f au lt va lu e s<br />

C o n s t r a i nt s<br />

I n h e r it a n c e<br />

S t at i c m e m b e r s<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!