Wednesday, January 16, 2008

Using a generic list of strings or other class objects

Microsoft has introduced a new concept of generics in C#.Net 2.0. It is a kind of design pattern, and a part of the .net type system which allows your code to define the type. A generic can be of intrinsic .net data type or some class object type.

Phew..!!! enough theory...let's get back to the real stuff! :-)

Okay, let say you have to define a list of some type say string, you can use generic List class for that purpose. But, remember first of all you'll have to include the following namespace:

using System.Collections.Generic;

Now declare the a list of strings as:

List strList = new List();

This list can contain strings which can be added, removed, or found using different methods, and provide more felxibility as compared to the array of strings.

strList.Add("some string");

Remove, Find, and other methods can also be used like this.

If you want to create a list of your own custom class objects, you can do that as well.

For example, you have a class named Customer, then below is the code to create a generic list of the objects of type customer:

List custList = New List();
Customer objCust = New Customer("Customer Name");

custList.Add(objCust);

You can also loop through the list of items as given below:

foreach(Customer objCustomer in custList)
{

//process objCustomer here

}

No comments: