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 ❘ 115<br />

With DocumentManager, all the titles of the documents should be displayed in the<br />

DisplayAllDocuments() method. The Document class implements the interface IDocument with the<br />

properties Title <strong>and</strong> Content:<br />

public interface IDocument<br />

{<br />

string Title { get; set; }<br />

string Content { get; set; }<br />

}<br />

public class Document: IDocument<br />

{<br />

public Document()<br />

{<br />

}<br />

public Document(string title, string content)<br />

{<br />

this.Title = title;<br />

this.Content = content;<br />

}<br />

}<br />

public string Title { get; set; }<br />

public string Content { get; set; }<br />

code snippet DocumentManager/Document.cs<br />

For displaying the documents with the DocumentManager class, you can cast the type T to the interface<br />

IDocument to display the title:<br />

public void DisplayAllDocuments()<br />

{<br />

foreach (T doc in documentQueue)<br />

{<br />

Console.WriteLine(((IDocument)doc).Title);<br />

}<br />

}<br />

code snippet DocumentManager/DocumentManager.cs<br />

The problem is that doing a cast results in a runtime exception if type T does not implement the interface<br />

IDocument. Instead, it would be better to define a constraint with the DocumentManager class<br />

that the type TDocument must implement the interface IDocument. To clarify the requirement in the name<br />

of the generic type, T is changed to TDocument. The where clause defines the requirement to implement the<br />

interface IDocument:<br />

public class DocumentManager<br />

where TDocument: IDocument<br />

{<br />

This way you can write the foreach statement in such a way that the type TDocument contains the property<br />

Title. You get support from Visual Studio IntelliSense <strong>and</strong> from the compiler:<br />

public void DisplayAllDocuments()<br />

{<br />

foreach (TDocument doc in documentQueue)<br />

{<br />

Console.WriteLine(doc.Title);<br />

}<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!