- Introduction
- Using Generic Collections
- Implementing a Generic Class
- Adding Type Constraints
- Summary
Using Generic Collections
A few myopic pundits have asked the question "Where is the promise of object-oriented programming (OOP)?" The answer is that there are two facets to OOP: the OOP that you consume and the OOP that you produce. If we simply look at all of the very advanced applications that couldn't have been written by consumers without OO frameworks such as Microsoft's .NET, Borland's VCL, and all the third-party components, we can say that OOP has lived up to its promise. Producing good OOP code is difficult and can be frustrating, but keep in mind that you don't have to produce OOP to benefit from it. So, let's first look at generics as consumers.
When you create projects in Visual Studio or one of the Express products, such as C# Express, you'll see a reference to the System.Collections.Generic namespace. In this one namespace are several generic data structures that support typed collections, hashes, queues, stacks, dictionaries, and linked lists. To use these powerful data structures, all you have to do is provide the data type.
Listing 1 shows how easily we can define a strongly typed collection of Customer objects.
Listing 1 This console application contains a Customer class and a strongly typed collection of Customers based on List<T>.
using System; using System.Collections.Generic; using System.Text; namespace Generics { class Program { static void Main(string[] args) { List<Customer> customers = new List<Customer>(); customers.Add(new Customer("Motown-Jobs")); customers.Add(new Customer("Fatman's")); foreach (Customer c in customers) Console.WriteLine(c.CustomerName); Console.ReadLine(); } } public class Customer { private string customerName = ""; public string CustomerName { get { return customerName; } set { customerName = value; } } public Customer(string customerName) { this.customerName = customerName; } } }
Notice that we have a strongly typed collection—List<Customer>—without writing a single line of code for the collection class itself. If we wanted to extend the customer list, we could derive a new class by inheriting from List<Customer>.