Generic is a type used to define a class, structure, interface, or method with placeholders to indicate that they can store or use one or more of the types. In C#, the compiler will replace placeholders with the specified type at compile time. We use generic frequently with collections.
Generics are useful for improving code reusability, type safety, and performance compared with non-generic types e.g. arraylist.
Here is a code sample;
//Generic example - using single generic type
public class Hospital<T> //Here <T> is a a placeholder beside Hospital class
{
private T Cases; //Declared a variable named "Cases" of type T
public Hospital(T value) //Constructor take another variable named value
{
this.Cases = value; //assinged received type to containting type "Cases"
}
public void Show()
{
Console.WriteLine(this.Cases);
}
}
Let’s implement this in our .NET6 main class;
Console.WriteLine("Hello, World!");
//use Hospital class
Hospital<int> x = new Hospital<int>(100); //replacing T with int
Hospital<string> y = new Hospital<string>("Hospital Cases");
x.Show();
y.Show();
We can use two generic types in a class;
//using two generic types
public class EliteHospital<T, U> //Here <T> is a a placeholder beside Hospital class
{
// PatientCount of type T
public T? PatientCount { get; set; }
//Docotrs of U
public U? Doctors { get; set; }
}
This is how we can use this;
Console.WriteLine("Hello, World!");
//using EliteHospital class
EliteHospital<int, string> xx = new EliteHospital<int, string>();
xx.PatientCount = 100;
xx.Doctors = "Available";
Console.WriteLine(xx.PatientCount);
Console.WriteLine(xx.Doctors);
Console.WriteLine("Press any key to continue..");
Console.ReadKey();
Add to favorites