Sunday, 17 December 2017

Generic in c#

Generic used to code reuse, type safety and increase performance, it consists in declaring a Type with Type parameter that will be instantiate. Declare generic with the help of <T> where T is the Parameterized type. Classes, Interfaces, Methods, Properties, Delegates can be used as a generic type.

Simple program to compare two string parameters using Compare method in CompareValue class.

using System;

namespace Generic
{
    class Program
    {
        static void Main(string[] args)
        {
            CompareValue check = new CompareValue();

            Console.WriteLine(check.Compare("A", "A"));

            Console.ReadKey();
        }
    }

    public class CompareValue
    {
        public bool Compare(string value1, string value2)
        {
            return value1.Equals(value2);
        }
    }
}

Output will be:
True


if check string parameter and integer parameter pass Compare method will throw errors

  Console.WriteLine(check.Compare("A", "123"));


Generic method:


using System;

namespace Generic
{
    class Program
    {
        static void Main(string[] args)
        {
            CompareValue check = new CompareValue();

            Console.WriteLine(check.Compare<string>("A", "A"));

            Console.ReadKey();
        }
    }

    public class CompareValue
    {
        public bool Compare<T>(T value1, T value2)
        {
            return value1.Equals(value2);
        }
    }
}


Output:
True


Generic Class:


using System;

namespace Generic
{
    class Program
    {
        static void Main(string[] args)
        {
            CompareValue<string> check = new CompareValue<string>();

            Console.WriteLine(check.Compare("A", "A"));

            Console.ReadKey();
        }
    }

    public class CompareValue<T>
    {
        public bool Compare(T value1, T value2)
        {
            return value1.Equals(value2);
        }
    }
}

Output:
True


Create integer generic class


using System;

namespace Generic
{
    class Program
    {
        static void Main(string[] args)
        {
            CompareValue<int> check = new CompareValue<int>();

            Console.WriteLine(check.Compare(100, 100));

            Console.ReadKey();
        }
    }

    public class CompareValue<T>
    {
        public bool Compare(T value1, T value2)
        {
            return value1.Equals(value2);
        }
    }
}

Output:
True


If pass parameter 100 , 200 output will be false value:

Console.WriteLine(check.Compare(100, 200));

Output will be:
False


No comments:

Post a Comment

Generic in c#

Generic used to code reuse, type safety and increase performance, it consists in declaring a Type with Type parameter that will be instant...