blog

Home / DeveloperSection / Blogs / Generic class in c#.

Generic class in c#.

Anonymous User13675 12-May-2011

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees and so on where operations such as adding and removing items from the collection are performed in much the same way regardless of the type of data being stored. Generic classes have the property that the type of objects they contains of little interest to the definer of the container class but of crucial importance to the user of the particular container. Therefore, the type of the contained object is an argument to the container class. The definer specifies the container class in terms of this argument and the user specifies what the type of the contained object is to be for the particular container.

In this blog, I will describe you that how to create a generic class in c#. One thing important is that generic class is also known as template class or parameterized class. Mainly we can use generic class to ensure type safety. Concept of a generic class is introduced in.Net framework 2.0 and we can see the use of the .net framework.

Creating generic class

For creating generic class our first step to declare a class by using a class keyword like the following example demonstrate.

public class GenericClass<G>

    }


This set of statements represent a generic class. Here we see one difference from the traditional class that we used <G> this words. Here G represents the parameter to class. When we create an object of GenericClass we tell that in which datatype this class will work. Like the following example demonstrates.

GenericClass<int> obj1 = new GenericClass<int>();  //This will work on int type variable.
GenericClass<double> obj2 = new GenericClass<double>();   //This will work on double type variable.


Here I will give you the following example which demonstrates the use of generic class in c#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ParametrizedClassDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            TemplateClass<string> strTemp = new TemplateClass<string>(2);   //This will create a string generic class.
            TemplateClass<int> intTemp = new TemplateClass<int>(3);    //This will create a int generic class.
            TemplateClass<double> doubleTemp = new TemplateClass<double>(2);    //This will create a double generic class.
            //adding string type value in template class.
            Console.WriteLine("Enter string value only.");
            for (int i = 0; i < strTemp.Count; i++)
            {
                Console.Write("Please eneter string value  :  ");
                strTemp.addValue(Console.ReadLine());
            }
            //Adding integer type value in template class
            Console.WriteLine("Enter integer value only.");
            for (int i = 0; i < intTemp.Count; i++)
            {
                Console.Write("Please Enter intetger value  :   ");
                intTemp.addValue(Convert.ToInt32(Console.ReadLine()));
            }
            //Adding integer type value in template class
            Console.WriteLine("Enter double value only.");
            for (int i = 0; i < doubleTemp.Count; i++)
            {
                Console.Write("Please Enter double value  :   ");
                doubleTemp.addValue(Convert.ToDouble(Console.ReadLine()));
            }
            //Displaying value...
            Console.WriteLine("Displaying string Concatnation.");
            string tempStr = "";
            for (int i = strTemp.Count - 1; i >= 0; i--)
            {
                tempStr += strTemp.getValue();
            }
            Console.WriteLine(tempStr);
            Console.WriteLine("Displaying addition of integer collection.");
            int tempInt = 0;
            for (int i = intTemp.Count - 1; i >= 0; i--)
            {
                tempInt += intTemp.getValue();
            }
            Console.WriteLine(tempInt);
            double tempDouble = 0.0;
            Console.WriteLine("Displaying double list.");
            for (int i = doubleTemp.Count - 1; i >= 0; i--)
            {
                tempDouble += doubleTemp.getValue();
            }
            Console.WriteLine(tempDouble);
            Console.ReadLine();
        }
    }
    public class GenericClass<G>
    {
   
    }
   
    //A template class. Wher <T> represents parameter in which type this class will work.
    class TemplateClass<T>
    {
        T[] arr = new T[0];   //Declaring an array of T type.
        int count = -1;   //Create an int variable count which have -1 as iniyial value.
        public TemplateClass(int arrLenght)
        {
            arr = new T[arrLenght];   //Allocating memory to T type array.
        }
        public int Count
        {
            get
            {
                return arr.Length;
            }
        }
        //This method will add value in arr T type array.
        public void addValue(T val)
        {
            count++;
            if (count < arr.Length)
            {
                arr[count] = val;
            }
            else
            {
                Console.WriteLine("Collection length overflow.");
            }
        }
        T val;
        //This method will used to return value from arr array.
        public T getValue()
        {
            val = arr[count];
            return val;
        }
    }
}
Output of following code snippet is as follows

Enter string value only.

Please enter string value  :  John

Please enter string value  :  Smith

Enter integer value only.

Please Enter enter value  :   45

Please Enter intetger value  :   66

Please Enter intetger value  :   88

Enter double value only.

Please Enter double value  :   22.1245

Please Enter double value  :   26.231

Displaying string Concatnation.

SmithSmith

Displaying addition of integer collection.

264

Displaying double list.

            52.462

Updated 18-Sep-2014
I am a content writter !

Leave Comment

Comments

Liked By