Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » 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.

Technologies: .NET 2.0, .NET 3.0 and 3.5,Visual C# .NET
Total downloads : 284
Total page views :  28154
Rating :
 4.2/5
This article has been rated :  5 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
GenericsInCSharpPartI.zip
 
Become a Sponsor


Related EbooksTop Videos



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


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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
GenericsInCSharpPartI.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Nice one!!! by Erode 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 | Delete | Modify | 
Main Use by Erode 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved