Search This Blog

Sunday, July 7, 2019

Generic in C#

1. Generic is  introduced in C# 2.0
2. Generic allow you to write a class or method that can work  with any data type
3. Generic class  or method can be defined using angle bracket
4 It help you maximize code reuse ,type safety(versatile datatype) and performance
5.You can create your own generic interface, class,methods ,events and delegates

// Generic Method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    class Exampe
    {
        // Generic Method
        public static void ShowArray<T>(T[] aArr)
        {
            for(int  i=0;i< aArr.Length; i++)
            {
                Console.WriteLine(aArr[i]);

            }

        }
        public static bool Check<T>( T a,T b)
        {
            bool lStatus = a.Equals(b);
            return lStatus;
        }
   

    }
    class Program
    {
        static void Main(string[] args)
        {
            int[] lNumbers = { 1, 2, 3 }; // Int Type Array
            string[] lName = { "monu", "sonu", "syam" }; // string Type Array
            double[] lPoint = { 0.01, 0.02, 0.03 }; // double Type Array
            //------------------ Call Multiple Method Using Generic------------------------
            Exampe.ShowArray(lNumbers);
            Exampe.ShowArray(lName);
            Exampe.ShowArray(lPoint);
            //------------------ Call Multiple Method Using Generic------------------------
            Console.WriteLine(Exampe.Check(10, 10));
            Console.WriteLine(Exampe.Check("Monu", "Sonu"));
            Console.WriteLine(Exampe.Check(0.1, 0.2));
            Console.ReadLine();
        }
    }
}
-----------------------------------------------------------------------------------------
// Generic Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
 
    class GenericClass<T>
    {
        T lbox;
        public GenericClass( T b)
        {

            this.lbox = b;
        }
        public T GetValue()
        {
         
            return lbox;
        }
   

    }
    class Program
    {
        static void Main(string[] args)
        {
            GenericClass<int> e= new GenericClass<int>(20);
            GenericClass<string> e1 = new GenericClass<string>("Johnson");
            Console.WriteLine(e.GetValue());
            Console.WriteLine(e1.GetValue());
            Console.ReadLine();
        }
    }
}


No comments :