jump to navigation

Generics in C# 2.0 and limitations of ArrayLists July 9, 2008

Posted by fofo in .NET, asp.net 2.0, C#.
Tags: ,
trackback

Most developers,students,enthusiasts who are are not that familiar with the .Net Framework, have been racing towards finding as much as possible about the latest version of the .Net Framework and more specifically LINQ, WPF, WCF e.t.c. Don’t get me wrong, I love the new features of C# 3.0,VB 9.0 and LINQ. But it is very important that we do understand the features introduced with the C# 2.0 and more specifically “Generics” which is in my opinion the most interesting feature introduced with C# 2.0. So I am going to take a break from talking about C# 3.0 new features and talk about Generics and why we should use them.

What is Generics anyway?

With .Net Framework 2.0 generic collections were introduced. A generic collection is basically a container that can be used to store objects of any class. What we do is we simply define a generic version of ArrayList by using the syntax of List<T>. T stands for type parameter, indicating that the type of the member objects in the list has not yet specified. We can replace with any class or object. T gets replaced by the data type at compile time. So we can have as an example(if we assume that we have already implemented a class called footballteam)

List<footballteam> fteam=new List<footballteam>();

fteam.Add(new footballteam(“Liverpool”);

fteam.Add(new footballteam(“Coventry”);

And why can’t I use other collection objects like ArrayList ? Type safety and performance, my friend.

With .Net 1.1 we had two kind of collection objects

With ArrayLists we could store objects in untyped collections, but using those it meant we said goodbye to our type safety. In order to demonstrate why we should use Generics and why type safety is important I will create a simple asp.net web application in c#.

1) Launch Visual Studio

2) Create a simple asp.net web application in c# and call it generics.

3) Add a button in the web form(default.aspx)

4) In the page load event handler type the following code

 ArrayList mynumbers = new ArrayList();
           

            mynumbers.Add(55);
            mynumbers.Add(75);
            mynumbers.Add(153);
            mynumbers.Add(45);

          
            int sum = 0;
            foreach (int number in mynumbers)
            {
                sum += number;
            }
            Response.Write(sum.ToString());

We just create an array of integers and then sum them.This code will compile just fine.

Right after this line of code

mynumbers.Add(45);

add this line of code

mynumbers.Add(“dotnet”);

and run your application.

You will notice that the compiler did not catch the obvious error. We are trying to add a literal string to integers. An invalid exception will appear when you click the button(at runtime obviously), System.InvalidCastException was unhandled by user code. Ideally we would like our compiler to catch this error, hence to give us the type safety that is desired.So we see that ArrayList lists are not typesafe. Why the compiler was not able to catch the obvious error in compile time?

Any value that is added to this list is implicitly upcasted to System.Object type.And what happens when we want to retrieve those values that they were upcasted? Well they are downcasted again to the appropriate type. Some of you might think that this is sort of cool. Well it is not, when it comes to performance.

When I type the following lines of code inside my button click event handler

ArrayList mynumbers = new ArrayList();
mynumbers.Add(55);

The Add method of the Arraylist class accepts a parameter of type Object.So when we add an integer value as we do in our example that value type has to be casted to an instance of type Object, as we said earlier. This process is also known as boxing. The reverse process is known as unboxing. If you use boxing and unboxing extensively in your object the application’s performance will decrease significantly.

Let’s see how we can rewrite the code inside the button click event handler using generics

Basically just replace this line of code

ArrayList mynumbers = new ArrayList();

with this one

List <int> mynumbers = new List<int>();

 and try to compile the application. It will fail and you will receive errors like the one below

The best overloaded method match for ‘System.Collections.Generic.List<int>.Add(int)’ has some invalid arguments C:\Users\fofo\dotnetprojects\generics\generics\Default.aspx.cs 

Generics enforce type checking at compile time only, so type safety is handled nicely by Generics .

Try to remember that you have to include this namespace in the beginning of your code

System.Collections.Generics

If you want to learn more about Generics click the links below

http://msdn.microsoft.com/en-us/library/0x6a29h6(VS.80).aspx

http://www.ondotnet.com/pub/a/dotnet/2004/05/17/liberty.html

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Comments»

1. sonj - July 23, 2008

Explained very well. Keep it up

2. Ashish - July 25, 2008

Very good article.

3. shivakanth - November 17, 2008

Explained very well
Thank You

4. Object Oriented Programming Concepts with C#3.0 « DOT NET RULES - June 21, 2009

[…] applies here. I have another single post on Generics and I do not see any point repeating […]

5. Ravi - July 15, 2009

Good :-) I got it now, nice explanation

6. Anil - January 28, 2010

thanx so much ji…. very nice tutorial.

7. suresh - December 30, 2010

good one………..keep it up

8. Manoj kumar yadav - January 26, 2012

nice explanation


Leave a comment