Generics is a new feature added in the .NET Framework 2.0. In this article we will look at what generics are and how they can be used to benefit the developer. The article is also supplemented with source code in Visual C#.NET.


Introduction:

Generics is a new feature added in the .NET Framework 2.0. In this article we will look at what generics are and how they can be used to benefit the developer. The article is also supplemented with source code in Visual C#.NET.

What are Generics?

If you are coming from a C++ background then you can easily relate generics to C++ templates. Generics allows you to use the same functionality using different types. Consider that your mother gives you a shopping list of items you need to buy. These items include shoes, vegetables, fruits and eggs, clothes. Now you go to a shoe store to buy shoes, you go to some grocery store to buy fruits, vegetables and eggs and finally you go to some mall to buy clothes. Wow! you are burning lot of gas and also wasting your time. Why not you just go to Wal-Mart and buy all the items.

In the same way you can use different data types with the same generic collection. The type of the collection should be specified

A Simple ArrayList():

Let's take a simple example of an ArrayList in which you can store any data type since it stores the type as object. This also means that when you store an integer value in the ArrayList it will be boxed and when its retrieved it has to be unboxed. This causes low performance. To learn more about Boxing and UnBoxing I recommend that you check my article "Boxing and UnBoxing in C#".

In the code below I am store different type of data into an ArrayList.

ArrayList myList = new ArrayList();

myList.Add("AzamSharp");

myList.Add("John Doe");

myList.Add("Mary");

myList.Add(23);

foreach (string str in myList)

{Console.WriteLine(str); // This will create a runtime exception

}

The problem as you have already noticed is when you retrieve the values from the ArrayList you don't know the type and hence it will throw an exception of "Invalid caste exception". This error is thrown at runtime when it tries to convert "23" to a string.

Using Generic List:

In this case you can use a generic list in which you can store the data which you specify. If any exception takes place than it you will see it at compile time rather than at compile time.

System.Collections.Generic.List<string> myStringList = new List<string>();

myStringList.Add("AzamSharp");

myStringList.Add("John Doe");

myStringList.Add(23); // compile time error will come here

In the example above I used the generic List type. I have indicated that my list will only contain strings and hence if I try to put any data type other than strings then it will create a compile time error rather than runtime.

Adding Objects to the Generic Collection:

You can easily add you objects to a generic collection. In the example below I have constructed a simple User.cs class which will later be added to the Generic List Collection.

using System;

using System.Collections.Generic;

using System.Text;

namespace GenericsDemo

{

class User

{

// field

private int _userID = 0;

private string _firstName = null;

private string _lastName = null;

// Constructor

public User(int userID,string firstName,string lastName)

{

_userID = userID;

_firstName = firstName;

_lastName = lastName;

}

// properties

public int UserID

{

get { return _userID; }

set { _userID = value; }

}

public string FirstName

{

get { return _firstName; }

set { _firstName = value; }

}

public string LastName

{

get { return _lastName; }

set { _lastName = value; }

}}}

}

 

Now we will make users and add to our generic collection:

Adding the objects to the generic collections is pretty simple. The List<T> collection exposes the Add method which can be used to add the object that you specify in the type.

/*

* As you can see in the method below that I have used Generic List to add

* User objects. Since its generic you can simply add anything in it.

*

* */

public static void GenericForCollection()

{

Console.WriteLine("*****GenericForCollection Method*******");

// Make a Generic Collection here

System.Collections.Generic.IList<User> userList = new List<User>();

// Create 5 users and add in the generic collection

for (int i = 1; i <= 5; i++)

{

// Make a user object and assign some properties

User user = new User(i,"John"+1,"Doe"+i);

// This is the cool thing now (Add in the generic collection)

userList.Add(user);

}

// print out the list of users from the Generic Collection

foreach (User user in userList)

{

Console.WriteLine("UserID: {0}",user.FirstName);

Console.WriteLine("FirstName: {0}", user.FirstName);

Console.WriteLine("LastName: {0}", user.LastName);

Console.WriteLine();

}}

 

Since we have specified that this collection will store the types of User objects any attempt to store other object will fail and will give you a compile time error. However you can successfully do this:

object o = null;

userList.Add((User)o); // casting an object type to the User Type

Generic Methods:

You can make Generic Methods, Properties, Interfaces, Classes etc. Below I have created a generic method that accepts a generic list type and a generic type variable. The method simply adds a new item to the list collection. 

/*

* A Generic method to add the item to the collection

* */

public static void Add<T>(List<T> list, T item)

{

list.Add(item);

}

Now, lets see how we can use the above method.

public void AddNewUser()

{

System.Collections.Generic.List<User> users = new List<User>();

Add(users, new User(45, "John", "Doe"));

Add(users, new User(12, "Mohammad", "Azam"));

// print the first name of the User

foreach (User u in users)

{

Console.WriteLine(u.FirstName);

}}

I am simply sending the Generic List and the User object that I need to be added and that's it. Now the cool thing is that you can use the same Generic Add Method to add different types of objects. Simply supply the generic list and the object that you need to add and it will be added to your list.

In the attached code samples I have implemented generic Find method as well as the Remove method. I hope you liked the article, happy coding!