Information Technology Reference
In-Depth Information
Generics in C#
With C# 2.0, Microsoft introduced the
generics
features, which offer more elegant ways of using
a set of code with more than one type. Generics allow you to declare
type-parameterized
code,
which you can instantiate with different types. What this means is that you can write the
code with “placeholders for types,” and then supply the
actual
types when you create an
instance of the class.
By this point in the text, you should be very familiar with the concept that a type is not an
object, but a template for an object. In the same way, a generic type is not a type, but a template
for a type. Figure 19-1 illustrates this point.
Figure 19-1.
Generic types are templates for types.
C# provides five kinds of generics: classes, structs, interfaces, delegates, and methods.
Notice that the first four are types, and methods are members.
Figure 19-2 shows how generic types fit in with the other types covered.
Figure 19-2.
Generics and user-defined types