Generics:
     
           
Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type. A simple example would help understanding the concept:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {
            G g = new G();
     g.Call();            
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice
{
    class G
    {
        class Generics<T>
        {
            public void equality(T x, T y)
            {
                if (x.Equals(y))
                { Console.WriteLine("paramater matched"); }
                else
                { Console.WriteLine("paramater didn't matched"); }
            }
        }
        public void Call()
        {
            Generics<int> ig = new Generics<int>();
            ig.equality(12, 8);
            Generics<string> sg = new Generics<string>();
            sg.equality("shoeb", "shoeb");
        }
    }
}
Output:
paramater
didn't matched
paramater
matched
 
No comments:
Post a Comment