In this article we are going to discuss the Generic classes in C#. There are many blogs, articles are available on the internet regarding Generic class but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Generic class in C#.
Generic Class Introduction
A Generic class defines the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on. Operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored.
Generic Classes Declaration
The Generic class can be defined by putting the <T> sign after the class name. Putting the "T" word in the Generic type definition isn't mandatory. You can use any word in the TestClass<> class declaration.
//Generic class
public class TestClass<T>{
}
Real World Example of Generic Class
A real-world example that demonstrates the power and utility of generic classes in C# is a generic repository pattern. The repository pattern is a popular way to abstract away the details of data access in an application. A generic repository allows for basic CRUD (Create, Read, Update, Delete) operations on any entity type, offering a flexible and reusable way to interact with the database without repeating code.
Example
let us understand static Class with an example. First, create a console application and then add a class file with the name Student.cs. Once you add the static class Student and add the following code.
// C# program to illustrate the concept of Generic class
using System;
// A generic class named GenericClass
public class GenericClass
{
private T genericField;
// Constructor that takes a parameter of type T
public GenericClass(T value)
{
genericField = value;
}
// Method that returns the value of the genericField
public T GetValue()
{
return genericField;
}
}
class Program
{
static void Main(string[] args)
{
// Creating an instance of GenericClass with type int
GenericClass intGenericObject = new GenericClass(50);
// Getting and printing the value of the generic field
Console.WriteLine("Value of int GenericObject: " + intGenericObject.GetValue());
// Creating an instance of GenericClass with type string
GenericClass stringGenericObject = new GenericClass("TutorialsTrens.Com!");
// Getting and printing the value of the generic field
Console.WriteLine("Value of String GenericObject: " + stringGenericObject.GetValue());
}
}
Output
Advantage of Generics
Here are some of the benefits of using generics in C#.