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
- OSError: cannot open resource - Python
- Python read file line count
- How to Encode & Decode using Base64 in Python?
- Unspecified error-The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support.
- How to generate a Captcha verification code image with Python?
- How to show an image using path python PIL?
- How to remove Background from the images using Python?
- Python generate QR code image
Related Article