Monday, 8 July 2013

Generics in c# with simple example

Generics were first introduced into the C# language in .NET 2.0. Most developers are confused about C# Generics. Generics allow us to define type-safe classes without worrying about type safety and performance. In other words, generics allow you to write a class or method that can work with any data type. By creating a generic class, you can create a collection that is type-safe at compile-time. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace. The generic class introduces a type parameter. 

Example
As shown in the following code:
  • Create a Generic Interface
  • Create a Generic Class and derive the interface into the Generic Class
  • Implement the methods of the Interface in the Generic Class
    // Generic Interface   
    interface ICustomInterface<T>
    {
        void Add(T item);
        void Remove(T item);
    }
    // Generic Class   
    class UserList<T> : ICustomInterface<T>
    {
        public int count;
        ArrayList list = new ArrayList();
        //Property to get the length of the list       
        public int Count
        {
            get           

            {
                return list.Count;
            }
        }
        //Generic method
        public void Add(T item)
        {
            list.Add(item);
        }
        //generic Method       
        public void Remove(T item)
        {
            list.Remove(item);
        }        
    }


In the code above, the UserList Class is built on ArrayList. ArrayList can store any type of object in it. Here T is the type you need to provide when creating the object. Now create the object for the UserList class and use the methods as follows.


// No boxing, no casting          
//Create a UserList object for integers

UserList<int> list = new UserList<int>();
//Add two integer values           
 list.Add(1);
list.Add(2);
//Write count of the list
Console.WriteLine(list.Count);
//Remove the items from list       
list.Remove(1);
list.Remove(2);          
// Try to add string to the list 
//compile time exception will rise
//(Argument '1': cannot convert from 'string' to 'int')
//
list.Add("text");

We can store any type of the objects into the UserList<T> object by giving the type you want to store while creating the UserList<T> objects. Generics can also be used in structures and delegates etcetera.

Benefits of Generics
The benefits of generics are:

  • Code reuse, type safety, and performance.
  • You can create your own generic interfaces, classes, methods, events and delegates.
  • The most common use of generics is to create collection classes.
  • Generic classes may be constrained to enable access to methods on particular data types.
  • Generics provide no boxing, no casting advantage.
  • Generics are checked at compile time.
------
Srinubabu Ravilla
Software Developer

No comments: