Section 14.1. Generics


14.1. Generics

Until generics, all the collection classes ( ArrayList , Stack , and Queue ) were defined to hold objects of type Object (the root class). Thus, you could add integers and strings to the same class, and when you took items out of the collection, you had to cast them to their "real" type. This was ugly, and it was error-prone (the compiler could not tell if you had a collection of integers and added a string).

With generics, the designer of the class (the person who creates the Stack class) can say, "This class will hold only one type, and that type will be defined by the developer who makes an instance of this class."

The user of the generic Stack class defines an instance of the Stack and the type it will hold, and the compiler can now use this type-safe Stack to ensure that only objects of the designated type are stored in the collection. Much better.

The designer adds a type placeholder (technically called a type parameter ):

 class Stack<T> 

The user of the Stack class puts in the actual type when instantiating the class, like this:

 class Stack<Employee> = new Stack<Employee> 



Learning C# 2005
Learning C# 2005: Get Started with C# 2.0 and .NET Programming (2nd Edition)
ISBN: 0596102097
EAN: 2147483647
Year: 2004
Pages: 250

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net