c# .net

Explain generics in c# example

Explain generics in c# example, someone asked me to explain?

Generics allow us to design classes and methods decoupled from data types. Generic classes available in System. Collections. Generic namespace. Generics make your code, type independent and that way you can reuse your code with any type. If you use generics you will get the strongest type nature and also get a performance gain from unnecessary boxing and unboxing.

Example:

If you want to compare two string or integer are equal.

To make CompareEqual() method generic , specify a type parameter using angular brackets as shown below

public static bool CompareEqual<T>(T Val1, T Val2)

Demo:

 
using System;
using System.Collections.Generic;
namespace Demoproject
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bool result = sample.CompareEqual<string>("infinetsoft", "infinetsoft");
            if (result)
            {
                HttpContext.Current.Response.Write("Equal");
            }
            else
            {
                HttpContext.Current.Response.Write("NotEqual");
            }
        }
    }

   public class sample
    {
        public static bool CompareEqual<T>(T Val1, T Val2)
        {
            return Val1.Equals(Val2);
        }
    }
}

Generic class:

If you want to use generic class, specify a type parameter using angular brackets as shown below

public class sample<T>

and invoke a method like

bool result = sample<string>.CompareEqual("infinetsoft", "infinetsoft"); 

Description: 

Here I am using string data type for comparison, likewise you can use any data type. T mentioned as a type parameter.

Post your comments / questions