menu

Sunday, August 25, 2013

Generic in C#

Generic is a term which enables us to design classes or methods which differ as per types until it is declared and instantiated. For exp …

using System;
namespace Generic
{
    class Program
    {
        public static void Main()
        {
            B<int> obj = new B<int>();
            System.Console.WriteLine(obj.Compare(2, 6));

            B<string> obj1 = new B<string>();
            System.Console.WriteLine(obj1.Compare("KUNAL", "MAURYA"));

            B<char> obj2 = new B<char>();
            System.Console.WriteLine(obj2.Compare('X', 'X'));

            ComplexNumber o1 = new ComplexNumber(2, 3);
            ComplexNumber o2 = new ComplexNumber(4, 8);
            B<ComplexNumber> obj3 = new B<ComplexNumber>();
            System.Console.WriteLine(obj3.Compare(o1, o2));

            Console.ReadKey();
        }
    }
    public class B  // Generic Class for all types having Equals method
    {
        public string Compare(myType a, myType b)
        {
            if (a.Equals(b))
            {
                return "Equal";
            }
            else
            {
                return "Not-Equal";
            }
        }
    }
    public class ComplexNumber
    {
        int a;
        int b;
        public ComplexNumber(int x, int y)
        {
            a = x;
            b = y;
        }
        public bool Equals(ComplexNumber z)
        {
            if (this.a.Equals(z.a) && this.b.Equals(z.b))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


No comments:

Post a Comment