Sunday, September 1, 2013

Using Generics in C#.net | Simple Example of generics .net

Using generics we can pass the data type as a parameter, thus it maximizes the code re-usability. The data type is passed while creating the object of that generic class. The datatype can be any thing like int,double,string, class etc.

Generics lets us create a type safe list at the compile time.

Example : Here we will use a Generic Method which will add for int type and concat for string type.

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

namespace ConsoleApplication2
{
    public class GenericList<T> // here T is a unknown data type
    {
        public T Add(T inputx,T inputy) {

            dynamic a = inputx;
            dynamic b = inputy;
            return a + b;
           
        }
    }
    public class Class1
    {
        static void Main(string[] args)
        {
            GenericList<int> list1 = new GenericList<int>();

            int result = list1.Add(10, 20);
            Console.WriteLine(result);
            //Console.ReadLine();

            GenericList<string> list2 = new GenericList<string>();

            string result2 = list2.Add("Chandan", " Singh");
            Console.WriteLine(result2);
            Console.ReadLine();
        }
    }
}

Output:



No comments:

Post a Comment