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.

5Generics<br />

WhaT ’ s in This ChaPTer<br />

➤<br />

➤<br />

➤<br />

➤<br />

➤<br />

➤<br />

An overview of generics<br />

Creating generic classes<br />

Features of generic classes<br />

Generic interfaces<br />

Generic structs<br />

G e n e r i c m e t h o d s<br />

Since the release of .<strong>NET</strong> 2.0, .<strong>NET</strong> has supported generics. Generics are not just a part of the <strong>C#</strong><br />

programming language, but are also deeply integrated with the IL (Intermediate Language) code<br />

in the assemblies. With generics, you can create classes <strong>and</strong> methods that are independent of<br />

contained types. Instead of writing a number of methods or classes with the same functionality for<br />

different types, you can create just one method or class.<br />

Another option to reduce the code is using the Object class. However, the Object class is not type -<br />

safe. Generic classes make use of generic types that are replaced with specifi c types as needed. This<br />

allows for type safety: the compiler complains if a specifi c type is not supported with the generic class.<br />

Generics are not limited to classes; in this chapter, you also see generics with interfaces <strong>and</strong><br />

methods. Generics with delegates can be found in Chapter 8, “ Delegates, Lambdas, <strong>and</strong> Events. ”<br />

generiCs oVerVieW<br />

Generics are not a completely new construct; similar concepts exist with other languages. For<br />

example, C++ templates have some similarity to generics. However, there ’ s a big difference between<br />

C++ templates <strong>and</strong> .<strong>NET</strong> generics. With C++ templates, the source code of the template is required<br />

when a template is instantiated with a specifi c type. Unlike C++ templates, generics are not only a<br />

construct of the <strong>C#</strong> language, but are defi ned with the CLR. This makes it possible to instantiate<br />

generics with a specifi c type in Visual Basic even though the generic class was defi ned with <strong>C#</strong>.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!