Please enable Javascript to correctly display the contents on Dot Net Tricks!

Difference between Generics and Collections with example

Posted By : Shailendra Chauhan, 30 Dec 2012
Updated On : 24 Jun 2014
Total Views : 283,507   
Support : C# 2.0, 3.0, 4.0, 5.0
 

Generics provides the type safe code with re-usability like as algorithm. In algorithms such as sorting, searching, comparing etc. you don’t specify what data type(s) the algorithm operates on. The algorithm can be operates with any types of data. In the same way Generics operate, you can provide different data type to Generics. For example, a sorting algorithm can operates on integer type, decimal type, string type, DateTime type etc.

In this article, I will demonstrate the advantage of Generics over Collections. Following are the main advantage of Generics.

Code Re-usability with Generics

Suppose, you required to sort the integer and floating type numbers, then let's see how to do in collections and generics.

How to do it using Collections

//Overloaded sort methods
private int[] Sort(int[] inputArray)
{
//Sort array
//and return sorted array
return inputArray;
}
private float[] Sort(float[] inputArray)
{
//Sort array
//and return sorted array
return inputArray;
}

How to do it using Generics

private T[] Sort(T[] inputArray)
{
 //Sort array
 //and return sorted array
 return inputArray;
}

Here, T is short for Type and can be replaced with the Type defined in the C# language at runtime. So once we have this method, we can call it with different data types as follows and can see the beauty of Generics. In this way Generics provide code re-usability.

Now if you thinking you can make fool to the compiler by passing an integer array while it is asking for a float, you are wrong. Compiler will shows the error at compile time like as:

Type Safety with Generics

Suppose, you want to make a list of students, then let's see how to do in collections and generics.

How to do it using Collections

In collections we can use ArrayList to store a list of Student objects like as:

class Student
{
public int RollNo{get; set;}
public string Name{get; set;}
}

//List of students
ArrayList studentList = new ArrayList();
Student objStudent = new Student();
objStudent.Name = "Rajat";
objStudent.RollNo = 1;

studentList.Add(objStudent);

objStudent = new Student();
objStudent.Name = "Sam";
objStudent.RollNo = 2;

studentList.Add(objStudent);

foreach (Object s in studentList)
{
//Type-casting. If s is anything other than a student
Student currentStudent = (Student)s;
Console.WriteLine("Roll # " + currentStudent.RollNo + " " + currentStudent.Name);
}

Problem with Collections

Suppose by mistake you have added a string value to ArrayList like as

studentList.Add("Generics"); //Fooling the compiler

Since ArrayList is a loosely typed collection and it never ensure compile-time type checking. Hence above statement will compile without error but it will throw an InvalidCastException at run time when you try to cast it to Student Type.

How to do it using Generics

In generics we can use generic List to store a list of Student objects like as:

List<Student> lstStudents = new List<Student>();

Student objStudent = new Student();
objStudent.Name = "Rajat";
objStudent.RollNo = 1;

lstStudents.Add(objStudent);

objStudent = new Student();
objStudent.Name = "Sam";
objStudent.RollNo = 2;

lstStudents.Add(objStudent);

//Looping through the list of students
foreach (Student currentSt in lstStudents)
{
//no need to type cast since compiler already knows that everything inside 
//this list is a Student
Console.WriteLine("Roll # " + currentSt.RollNo + " " + currentSt.Name);
}

Advantage with Generics

In case of collections you can make fool to compiler but in case of generics you can't make fool to compiler as shown below. Hence Generics provide Type Safety.

Cleaner Code with Generics

Since compiler enforces type safety with Generics. Hence fetching data from Generics doesn't required type casting which means your code is clean and easier to write and maintain.

Better Performance with Generics

As you have seen in above example, at the time of fetching the data from the ArrayList collection we need to do type casting which cause performance degrades. But at the time of fetching the data from the generic List we don't required to do type casting. In this way Generics provide better performance than collections.

What do you think?

I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

 
Recommended for you
 
About the Author
Shailendra Chauhan

Shailendra Chauhan is an Entrepreneur, Author, Architect, and Corporate Trainer. He has rewarded as Microsoft MVP for his exceptional contributions in Microsoft Visual Studio and Development Technologies.

With more than 7 years in hand experience Shailendra Chauhan is a polymath in the domains of Microsoft .NET technologies and an array of other technologies including JavaScript, AngularJS, Node.js, Ionic and NoSQL Databases to name but a few.

He is the author of some of most popular e-books which encompass technical Interview on Node.js Interview Questions and Answers , ASP.NET MVC Interview Questions and Answers , AngularJS Interview Questions and Answers and LINQ Interview Questions and Answers. Furthermore he is a technical reviewer for book on ASP.NET MVC 4 Mobile App Development. Know more...
 
Free Interview Books
 
4 AUG
NodeJS Development (online)

Thursday 06:00 AM-7:30 AM IST

More Details
1 AUG
AngularJS Development (online)

Mon-Fri 09:00 PM-10:30 PM IST

More Details
29 JUL
ASP.NET MVC with AngularJS Development (online)

Mon-Fri (07:30 AM-09:00 AM IST)

More Details
24 JUL
AngularJS Development (offline)

Sat,Sun     (08:00 AM-09:30 AM)

24 JUL
ASP.NET MVC with AngularJS Development (offline)

Sat, Sun     (09:30 AM-11:00 AM)

28 MAY
ASP.NET MVC with AngularJS Development (offline)

Sat, Sun     (05:00 PM-07:00 PM IST)

30 APR
NodeJS Development (offline)

Sat, Sun     (11:00 AM-12:30 PM IST)

BROWSE BY CATEGORY
 
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 
+