Tuesday, February 6, 2007

A simple case for List<T> in System.Collections.Generic

List<T> in System.Collections.Generic namespace can be sort of equated to ArrayList in System.Collections namespace. However, Generics are the most powerful feature of C# 2.0. Generics allow us to define type-safe data structures, without committing to actual data types. A simple example to demonstrate the ease of this could be done thinking about an OrderItem class; let’s say we define the OrderItem class as:

public class OrderItem

{

public string OrderID = string.Empty,

ProductID = string.Empty,

Quantity = string.Empty;

public OrderItem (string orderID, string productID, string qty)

{

OrderID = orderID;

ProductID = productID;

Quantity = qty;

}

}

To define a list of OrderItem in your shopping cart or other locations, then, all we need to do is:

List<OrderItem> orderItems = new List<OrderItem>();

To add items to the List of OrderItems, all we need to do is:

orderItems.Add(new OrderItem("Order123", "Product234", "3"));

orderItems.Add(new OrderItem("Order123", "Product001", "1"));

Notice that we didn’t declare the size of the OrderItem and we can go on adding items by using the Add method. Do we want to loop through all items, use foreach; do we want to find an item, use find. There are many more properties, methods and advanced advantages for using Generics, but this is a simple case to give the gist of such usage.

Love coding!

No comments: