Wednesday, December 15, 2010

C#.net - Generic in C#.net

What is Generic?

C# Generics is 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.

Why Generics?
  • Generics let us to specify our Type at runtime. you can create a collection that is type-safe at compile-time.
  • Gives no boxing, no casting advantage.
  • Both the casting and the boxing and unboxing operations degrade performance.
  • Use of list collection as their new type not as objects.
  • Binary code reuse
  • Code clearness with generics is another advantage.
Let us take an example of creating Generic collection using the simple example below. Requirement is to create the collection of Teaching Staff and NonTeaching Staff.

Step 1
Create a Console Application and give the name as ConGenericClass.

Step 2
Create a TeachingStaff class in the solution,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConGenericClass
{
    public class TeachingStaff
    {
        #region Constructor

        /// <summary>
        /// Blank Constructor
        /// </summary>
        public TeachingStaff()
        { 
        
        }

        /// <summary>
        /// Add Teaching Staff Data
        /// </summary>
        /// <param name="FirstName">Specify First Name</param>
        /// <param name="LastName">Specify Last Name</param>
        /// <param name="Age">Specify Age</param>
        public TeachingStaff(String FirstName,String LastName,int Age)
        {
            try
            {
                this.FirstName = FirstName;
                this.LastName = LastName;
                this.Age = Age;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

        #region Property

        public String FirstName
        {
            get;
            set;
        }

        public String LastName
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }
        #endregion
    }
}

Step 3
Create a NonTeachingStaff class in solution,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConGenericClass
{
    public class NonTeachingStaff
    {
        #region Constructor

        /// <summary>
        /// Blank constructor
        /// </summary>
        public NonTeachingStaff()
        { 
        }

        /// <summary>
        /// Add Non Teaching Staff Data
        /// </summary>
        /// <param name="FirstName">Specify First Name</param>
        /// <param name="LastName">Specify Last Name</param>
        /// <param name="Age">Specify Age</param>
        public NonTeachingStaff(String FirstName, String LastName, int Age)
        {
            try
            {
                this.FirstName = FirstName;
                this.LastName = LastName;
                this.Age = Age;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }
        #endregion

        #region Property

        public String FirstName
        {
            get;
            set;
        }

        public String LastName
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }

        #endregion
    }
}

Step 4
Now create a Generic teacher class which can hold the collection of either Teaching staff data or Non Teaching Staff Data.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConGenericClass
{
    public class Teacher<T>:IEnumerable<T>
    {
      
        #region Declaration

        private List<T> ListObj = new List<T>(); // Create a object List Class

        #endregion

        #region Methods

        /// <summary>
        /// Add Data in List Object
        /// </summary>
        /// <param name="TObj"></param>
        public void Add(T TObj)
        {
            try
            {
                ListObj.Add(TObj); // Add data in List  
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

      

        #endregion


        #region IEnumerable Methods

        public IEnumerator<T> GetEnumerator()
        {
                foreach (T TObj in ListObj)
                {
                    yield return TObj; 
                }
           
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            try
            {
                return GetEnumerator(); 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion
    }
}

Naming Guideline
  • Generic type name should be prefixed with letter T.
  • If the generic type can be replaced by any class because there no special requirement and only one generic type is used,the character T is good as generic type name:
    • public class List<T>
Implement IEnumerable<T> interface
Exposes the enumerator, which supports a simple iteration over a collection of a specified type.
Enumerates through a collection using a foreach statement.

Step 5
Now we can use the Generic teacher collection to hold either the teaching staff data or non teaching staff data collections.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConGenericClass
{

    class Program
    {
        static void Main(string[] args)
        {
            #region Add Data

                #region Teaching Staff Data
            
                    Teacher<TeachingStaff> TeachingStaffObj = new Teacher<TeachingStaff>();
            
                    TeachingStaffObj.Add(new TeachingStaff("Kishor", "Naik", 24));
                    TeachingStaffObj.Add(new TeachingStaff("Bhavesh", "Pisat", 24));

                #endregion

                #region Non Teaching Staff Data

                    Teacher<NonTeachingStaff> NonTeachingStaff = new Teacher<NonTeachingStaff>();

                    NonTeachingStaff.Add(new NonTeachingStaff("Ramdas", "Bhosale", 25));
                    NonTeachingStaff.Add(new NonTeachingStaff("Bhushan", "Pawar", 27));

                #endregion

            #endregion

            #region Print Data

                #region Print Teaching Staff Data

                        System.Console.WriteLine("Teaching Staff Data");

                        System.Console.WriteLine("FirstName\t LastName\t Age");
                        System.Console.WriteLine();
 
                        foreach (TeachingStaff TS in TeachingStaffObj)
                        {
                            System.Console.Write(TS.FirstName+"\t\t "+TS.LastName+"\t\t "+TS.Age);
                            System.Console.WriteLine(); 
                        }
                        System.Console.WriteLine("\n\n");  

                #endregion

                #region Print Non Teaching Staff Data

                        System.Console.WriteLine("Non Teaching Staff Data");

                        System.Console.WriteLine("FirstName\t LastName\t Age");
                        System.Console.WriteLine();

                        foreach (NonTeachingStaff NTS in NonTeachingStaff)
                        {
                            System.Console.Write(NTS.FirstName + "\t\t " + NTS.LastName + "\t\t " + NTS.Age);
                            System.Console.WriteLine(); 
                        }
                        

                #endregion

            #endregion


        }
    }
}


Run the project.

Download
Download Source Code

No comments:

Post a Comment