Menu Close

GENERICS IN C#

GENERICS IN C#



GENERICS

Generics are introduced in c# 2.0. Generics allow us to design classes and methods deoupled from the data types.

Generics classes are extresively used by collection classes available in System.Collections.Generic namespace.(Covered in the next session)

One way of making AreEqual() method resuable, is to use object type parameters. Since, every type in .NET directly onherit from System.Object type, AreEqual() method works with any data type, but the probelm is performance degradation due to boxing and unboxing happening.

Also, AreEqual() method is no longer type safe. It is now possible to pass integer for th first parameter, and string for the second parameter.It doesn’t really make sense to compare strings with integers.

So, the problem with using System.Object.type is that
1. AreEqual() method is not type safe
2. Performance degradation due to boxing and unboxing.

————————————————————————————————————————–
using System;
using System.Reflection;

namespace ConsoleApplication4
{
    public class MainClass
    {
        private static void Main()
        {
            bool Equal = Calculator.AreEqual<int>(10,10);
            if (Equal)
            {
                Console.WriteLine(“Equal”);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine(“Not Equal”);
                Console.ReadLine();
            }
        }

    
    }


    public class Calculator
    {
        public static bool AreEqual<T>(T Value1, T Value2)
        {
            return Value1.Equals(Value2);
        }

    }
}

Share this:
Posted in Blog

Related Posts