Lesson 28
Making Generic Classes
The section “Generic Classes” in Lesson 16 explained how to use generic collection classes. For example, the following code defines a list that holds Employee
objects:
public List<Employee> Employees = new List<Employee>();
This list can only hold Employee
objects, and when you get an object out of the list, it has the Employee
type instead of the less-specific object
type.
Lesson 16 also described the main advantages of generic classes: code reuse and specific type checking. You can use the same generic List<>
class to hold a list of string
s, double
s, or Person
objects. By requiring a specific data type, the class prevents you from accidentally adding an Employee
object to a list of Order
objects, and when you get an object from the list you know it is an Order
.
In this lesson, you learn how to build your own generic classes so you can raise code reuse to a whole new level.
Defining Generic Classes
A generic class declaration looks a lot like a normal class declaration with one or more generic type variables added in angled brackets. For example, the following code shows the basic declaration for a generic TreeNode ...
Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.