What is Generics in C#? Example.

Question 1. What Is Generics?
Answer :
Generics are the most powerful features introduced in C# 2.0. It is a type-safe data structure that allows us to write codes that works for any data types.
Question 2. What Is A Generic Class?
Answer :
A generic class is a special kind of class that can handle any types of data. We specify the data types during the object creations of that class. It is declared with the bracket <>. For example consider the following Comparer class, which has a method that compare two value and returns as Boolean output.
public class Comparer
{
    public bool Compare(Unknown t1, Unknown t2)
  {  
         if (t1.Equals(t2))
      {
            return true;
        }
        else
        {
            return false;
        }
    }
}
Comparer oComparerInt = new Comparer();
Console.WriteLine(oComparerInt.Compare(10, 10));
Comparer oComparerStr = new Comparer();
Console.WriteLine(oComparerStr.Compare("jdhsjhds", "10"));
Question 3. Why We Should Use Generics?
Answer :
Generic provides lot of advantages during programming. We should use generics for the following reasons:
It allows creating class, methods which are type-safe
It is faster. Because it reduce boxing/un-boxing
It increase the code performance
It helps to maximize code reuse, and type safety
Share:

No comments:

Post a Comment

Tuesday, 2 July 2019

What is Generics in C#? Example.

Question 1. What Is Generics?
Answer :
Generics are the most powerful features introduced in C# 2.0. It is a type-safe data structure that allows us to write codes that works for any data types.
Question 2. What Is A Generic Class?
Answer :
A generic class is a special kind of class that can handle any types of data. We specify the data types during the object creations of that class. It is declared with the bracket <>. For example consider the following Comparer class, which has a method that compare two value and returns as Boolean output.
public class Comparer
{
    public bool Compare(Unknown t1, Unknown t2)
  {  
         if (t1.Equals(t2))
      {
            return true;
        }
        else
        {
            return false;
        }
    }
}
Comparer oComparerInt = new Comparer();
Console.WriteLine(oComparerInt.Compare(10, 10));
Comparer oComparerStr = new Comparer();
Console.WriteLine(oComparerStr.Compare("jdhsjhds", "10"));
Question 3. Why We Should Use Generics?
Answer :
Generic provides lot of advantages during programming. We should use generics for the following reasons:
It allows creating class, methods which are type-safe
It is faster. Because it reduce boxing/un-boxing
It increase the code performance
It helps to maximize code reuse, and type safety

No comments:

Post a Comment

Popular

Total Pageviews

Archive