SIGN UP MEMBER LOGIN:    
ARTICLE

An Introduction to C# Generics

Posted by John Hudai Godel Articles | Visual C# February 06, 2006
Tags: C#, Generics, Godel, John
There is a reality; most of the developers confuse about C# Generics. Actually, there is no reason for that. If your background comes from C++ or Java you may understand more easily. What “Templates” tell you from your C++ knowledge or “Generics” from Java.
Reader Level:

There is a reality; most of the developers confuse about C# Generics. Actually, there is no reason for that. If your background comes from C++ or Java you may understand more easily. What "Templates" tell you from your C++ knowledge or "Generics" from Java. Main concept is same here in C# with some better extensions and easy usability. For example since C++ Templates uses compile time, C# Generics also a feature of the runtime. They are basically the capacity to have type parameters lying on your type. Generics refer to classes and methods that work homogeneously on values of different types. They are a type of data structure that contains code that remains the same; though, the data type of the parameters can change with each use. We can also call them parameterized types or parametric polymorphism.

 

The usage of generics within the data structure adjusts to the different data type of the passed variables. Briefly, a generic is a code template that can be applied to use the same code over and over again. Whenever the generic is used, it can be adapted for different data types without require to rewrite any of the internal code.

 

A List collection class can be a good example:

 

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

 

// No boxing or casting necessary

list1.Add (5);

 

If we want to expand this code and make it more sensible, we can build something like this:

 

using System;

using System.Collections;

using System.Text;

 

namespace TList

{

    public class List<Template> : CollectionBase

    {

        public List(){ }

 

        public Template this[int index]

        {

            get { return (Template)List[index]; }

            set { List[index] = value; }

        }

 

        public int Add(Template value)

        {

            return List.Add(value);

        }

    }

}

 

If we decide to convert any fields to generic fields, we would just change their types to Template. The generic List doesn't need any fields, but assume a private integer field named test is exist that we would like to make it generic. Here is the sample code:

 

private Template test;

 

Generics allow classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate. We can refer to a class, where we don't force it to be related to any specific Type, except we can perform work with it in a Type-Safe approach. We can create a generic collection than can handle any Type in a generic and Type-Safe approach. For example, we can have a single array class to store a list of Employees or yet a list of Items, and as we actually use it, we will be able to access the items in the collection directly as a list of Employees or Items, and not as objects.

 

Why Generics?

  1. Generics let us to specify our Type at runtime. you can create a collection that is type-safe at compile-time.
  2. Gives no boxing, no casting advantage.
  3. Both the casting and the boxing and unboxing operations degrade performance.
  4. Use of list collection as their new type not as objects.
  5. Binary code reuse
  6. Code clearness with generics is another advantage. 

In this short article we saw the basic advantages of generic types and how their use can improve type safety, code reuse, and performance. We also got a taste of the syntax in C# and saw how generics guide to an additional point of indirection, consequential in better flexibility. Now C# programmer has much stronger and flexible technology to use in their code.

Login to add your contents and source code to this article
share this article :
post comment
 

Can Generics be inherited?

Posted by Lalit Singh Apr 29, 2011

thanx check this helpful link http://www.mindstick.com/Articles/62f1e1b7-4f54-4d29-8c59-aa08d1190db1/?Collection%20and%20Generic%20Collection%20Classes%20in%20C%20NET

Posted by raj gupta Feb 01, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • 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.
    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.
Nevron Gauge for SharePoint
Become a Sponsor