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
Recent Article
- How to add two numbers in Android Studio? | Source Code
- FindViewByID returns null in android studio -SOLVED
- Saving changes is not permitted in SQL SERVER - [SOLVED]
- Restore of database failed. File cannot be restored over the existing. -[SOLVED]
- One or more projects in the solution were not loaded correctly in Visual Studio 2019 | FIXED
- How to find Laptop's Battery Health?
- SOLVED-Related Field got invalid lookup: icontains error in Django
- How to enable Search Feature in Django admin?
Related Article