Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » Visual C# » Generics in C# - Part I

Generics in C# - Part I

In part I of this series you will see the importance of generics, you will know how to use generics types which in System.Collections.Generic, and you will also know how to create generic methods.

Page Views : 59938
Downloads : 559
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GenericsInCSharpPartI.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



Introduction:

Generics gives you the ability to create a generic methods or a generic type by defining a placeholder for method arguments or type definitions, which are specified at the time of invoking the generic method or creating the generic type.
 
Why Generics?
To understand the importance of generics let's start by seeing some kind of problems which can be solved by it.
 
ArrayList:

Let's start by creating an ArrayList to hold stack-allocated data.
 
ArrayList intList = new ArrayList();
 
As you may know, the ArrayList collection can receive and return only Object type, so the runtime will convert the value type (stack-allocated) automatically via boxing operation into Object (heap-allocated).

ArrayList intList = new ArrayList();
//add a value type to the collection(boxing)
intList.Add(5);

To retrieve the value from the ArrayList you must unbox the heap-allocated object into a stack-allocated integer using a casting operation.

//unboxing
int x = (int)intList[0];
 
The problem with the stack/heap memory transfer is that it can have a big impact on performance of your application because when you use boxing and unboxing operations the following steps occur:

  1. A new object must be allocated on the managed heap.
  2. The value of the stack-allocated type must be transferred into that memory location.
  3. When unboxed, the value stored on the heap must be transferred back to the stack.
  4. The unused object on the heap will be garbage collected.

Now consider that you ArrayList contained thousands of integers that are manipulated by your program, this for sure will affect on you application performance.

Custom Collections:

Assume that you have to create a custom collection that can only contain objects of Employee type.

public class Employee

{

    string FirstName;

    string LastName;

    int Age;

   

    public Employee(){}

    public Employee(string fName, string lName, int Age)

    {

        this.Age = Age;

        this.FirstName = fName;

        this.Lastname = lName;

    }

    public override string ToString()

    {

        return String.Format("{0} {1} is {2} years old", FirstName, LastName, Age);

    }

}

Now we will build the custom collection 

public class EmployeesCollection : IEnumerable

{

    ArrayList alEmployees = new ArrayList();

    public EmployeesCollection() { }

 

     //Insert Employee type

     public void AddEmployee(Employee e)

     {

        //boxing

        alEmployees.Add(e);

    }

 

    //get the employee type

    public Employee GetEmployee(int index)

    {

        //unboxing

        return (Employee)alEmployees[index];

    }

 

    //to use foreach

    IEnumerator IEnumerable.GetEnumerator()

    {

        return alEmployees.GetEnumerator();

    }

}
 
The problem here is that If you have many types in you application, you have to create multiple custom collections one for each type.And as you can see we also have the problem of boxing and unboxing here.
 
All problems you saw previously can be solved using generics, so let's see what we can do.
 
The System.Collections.generic namespace:
 
You can find a lot of generic collections in the System.Collections.Generic just like:

  1. List<T>
  2. Dictionary<K, V>
  3. Queue<T>
  4. Stack<T>

Generic collections allows you to delay the specification of the contained type until the time of creation.
 
By using the generic collection you avoid performance problems of the boxing and unboxing operations and don't need to create a custom collection for each type in you application.
 
With the generic collections it's up to you to define the type which will be contained in the collection by replacing the placeholder T by the type you want at the time of creation.
 
List<T>
 
The List<T> is a generic collection that represents a strongly typed list of objects that can accessed by index. It is just like the nongeneric collection ArrayList. 
 
Example:

//Can only contain int type

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

 

//no boxing

intList.Add(10);

 

//no unboxing

int x = intList[0];

 

//Can only contain Employee objects

List<Employee> empList = new List<Employee>();

 

//no boxing

empList.Add(new Employee("Amr", "Ashush", 23));

 

//no unboxing

Employee e = empList[0]; 

Queue<T>

Queue<T> is a generic collection that represents a first-in, first-out (FIFO) collection of objects. It is just like the nongeneric collection Queue.

Example:

//A generic Queue collection

Queue<int> intQueue = new Queue<int>();

 

//Add an int to the end of the queue

//(no boxing)

intQueue.Enqueue(5);

 

//Returns the int at the beginning of the queue

//without removing it.

//(no unboxing)

int x = intQueue.Peek();

 

//Removes and returns the int at the beginning of the queue

//(no unboxing)

int y = intQueue.Dequeue(); 

Stack<T>
 
Stack<T> is a generic collection that represents a last-in-first-out (LIFO) collection of instances of the same arbitrary type. It is just like the nongeneric collection Stack.
 
Example:

Stack<int> intStack = new Stack<int>();

 

//Insert an int at  the top of the stack

//(no boxing)

intStack.Push(5);

 

//Returns the int at the top of the stack

//without removing it.

//(no unboxing)

int x = intStack.Peek();

 

//Removes and returns the int at the top of the stack

//(no unboxing)

int y = intStack.Pop();


Dictionary<K, V>
 
Dictionary<K, V> is a generic collection that contains data in Key/Value pairs, it is just like the nongeneric collection Hashtable.
 
Example:

Dictionary<string, string> dictionary = new Dictionary<string, string>();

 

//Add the specified key and value to the dictionary

dictionary.Add("Key", "Value");

 

//Removes the value with the specified key from the dictionary

dictionary.Remove("Key");

 

//get the number of the Key/Value pairs contained in the dictionary

int count = dictionary.Count;
 
Generic Methods
 
You can create generic methods that can operate on any possible data type.
To define a generic method you specify the type parameter after the method name and before the parameters list.
 
Example:

public void MyGenericMethod<T>(T x, T y)

{

    Console.Writeline("Parameters type is {0}", typeof(T));

}

 

You can define the type you want at the time you invoke the method.

 

int x, y;

MyGenericMethod<int>(x, y);

 

The result will be

Parameter type is System.Int32

 

string x, y;

MyGenericMethod<string>(x, y);
 
The result will be
Parameter type is System.String
  
You can also create a generic method with out parameters as follow:


 

public void MyGenericMethod<T>()

{

    T x;

    Console.WriteLine("The type of x is  {0}", typeof(T));

}
 
Here we see the method in use:
 
MyGenericMethod<int>();
 
The result will be:
The type of x is System.Int32
 
MyGenericMethod<string>();
 
The result will be:
The type of x is System.String
 
Note: you can omit the type parameter if the generic method requires arguments, because the compiler can infer the type parameter base on the member parameters. However if you generic method doesn't take any parameters you are required to supply the type parameter or you will have a compile error
 
Example: 
 

//a generic method that take two parameters

public void MyGenericMethod<T>(T x, T y)

{

    ......

}

......

 

string x, y;

//the compiler here will infer the type parameter

MyGenericMethod(x, y)


In the case of a generic method that doesn't take parameters

//a generic method that doesn't take parameters

public void MyGenericMethod<T>()

{

    ......

}

 

//you must supply the type parameter

MyGenericMethod<string>();

 

//you will have a compiler error here

MyGenericMethod();
 
In Part II you will see how to create generic classes, structures, delegates, interfaces and you will know how to create a custom generic collection.

Part I - Part II

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Amr Monjid
Amr Monjid is a computer programmer from Egypt. He has experience with C#, .Net framework, ASP.NET, Windows Applications, ADO.NET, Xml, Web Services, Custom Controls, and e-commerce web sites. and he is a MCTS: .NET framework 2.0, Windows Application, Distributed Aplication.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Nice one!!! by Senthilkumar On August 6, 2009
Hey Amr Monjid,

Your article looking pretty good.

I have one doubt. If you stored an object in the ArrayList then it will be stored on the heap memory. If you do unboxing then it needs to be converted into value type. Of course the value type will be stored on the stack. But in this scenario, after unboxing the data will be there in same position as it is in the heap memory.But it will add the memory location address to the stack.

Please verify that.

Thanks.
Erode Senthilkumar
Reply | Email | Modify 
Re: Nice one!!! by XX On December 6, 2009
yes skumaar that's true
Even though objects are held on heap, references to them are also variables and they are placed on stack.
Reply | Email | Modify 
Main Use by Senthilkumar On August 6, 2009
Hi Amr Monjid,

You have said like if we store 1000 int items on the stack and while retrieving the items we have to do the unboxing. It will affect the performance. Yes! its right!!

Here i would like to add one more important use of Generics.

Consider a scenario like if we are going to store the some integer value in the stack. Then we are going to iterate the stack and add the value. For that we have to unboxing, that time of there is some string values there. That time it will throw the type casting error.

Its run time error. This error was unavoidable up to .Net 1.1. This issue was rectified in the .Net 2.0.

If you use the Generics then it will give the compile time error instead of run time error.

Thank you

Erode Senthilkumar
Reply | Email | Modify 
Good articles Mr. Egyptian by Mohammed On May 6, 2010
Your articles here are so great, Thanks alot
Reply | Email | Modify 
very good illustrated...! by Rahul On November 15, 2010
thank u lot.....
Reply | Email | Modify 
h by venkat On March 18, 2011
h
Reply | Email | Modify 
Many thanks by Badiya On September 25, 2011
It was very useful for me.
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.