15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

114 ❘ ChaPTer 5 Generics<br />

Let ’ s start this example with a generic document manager. The document manager is used to read <strong>and</strong> write<br />

documents from a queue. Start by creating a new Console project named DocumentManager <strong>and</strong> add the<br />

class DocumentManager < T > . The method AddDocument() adds a document to the queue. The read - only<br />

property IsDocumentAvailable returns true if the queue is not empty:<br />

using System;<br />

using System.Collections.Generic;<br />

namespace Wrox.ProCSharp.Generics<br />

{<br />

public class DocumentManager < T ><br />

{<br />

private readonly Queue < T > documentQueue = new Queue < T > ();<br />

public void AddDocument(T doc)<br />

{<br />

lock (this)<br />

{<br />

documentQueue.Enqueue(doc);<br />

}<br />

}<br />

}<br />

}<br />

public bool IsDocumentAvailable<br />

{<br />

get { return documentQueue.Count > 0; }<br />

}<br />

code snippet DocumentManager/DocumentManager.cs<br />

default Values<br />

Now you add a GetDocument() method to the DocumentManager < T > class. Inside this method the type T<br />

should be assigned to null . However, it is not possible to assign null to generic types. The reason is that<br />

a generic type can also be instantiated as a value type, <strong>and</strong> null is allowed only with reference types. To<br />

circumvent this problem, you can use the default keyword. With the default keyword, null is assigned<br />

to reference types <strong>and</strong> 0 is assigned to value types:<br />

public T GetDocument()<br />

{<br />

T doc = default(T);<br />

lock (this)<br />

{<br />

doc = documentQueue.Dequeue();<br />

}<br />

return doc;<br />

}<br />

T he default keyword has multiple meanings depending on the context where it is<br />

used. The switch statement uses a default for defi ning the default case, <strong>and</strong> with<br />

generics default is used to initialize generic types either to null or 0 depending on if<br />

it is a reference or value type.<br />

C ons t raint s<br />

If the generic class needs to invoke some methods from the generic type, you have to add constraints.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!