Generic Class in C#

Generics in one of the most powerful features of C#, which was introduced in C# 2.0. Before generics, programmers used to use "object" type, to store value of any type, but it would require programmers to remember object type and it leads to various run-time errors. So, C# provides generics to remove the need for casting, improve type safety, reduce the amount of boxing required, and make it easier to create generalized classes and methods.

Generic classes and methods accept type parameters, which specify the types of objects on which they operate. In C#, you indicate that a class is a generic class by providing a type parameter in angle brackets, like this

public class Queue<T> {
   //members of class here
} 

Where, T in this example acts as a placeholder for a real type at compile time. When you write code to instantiate a generic Queue, you provide the type that should be substituted for T (Circle, Horse, int, and so on).

Example of Generic Class in C#

Let's take a look at an complete example of a Generic class in which we will be creating a class, which can be used for multiple data-types.

using System;
					
public class GenericClassProgram
{
	public static void Main()
	{		
		GenericClass<int> intClass = new GenericClass<int>();
		//passed as int type
		intClass.DoSomething(4);
		
		GenericClass<string> stringClass = new GenericClass<string>();
		//passed as string
		stringClass.DoSomething("44");
	}
	
	public class GenericClass<T>
	{
		public void DoSomething(T item)
		{
		   Console.WriteLine(item);
		}
	}
}

Output:

4
44

As you can see in the above code, we are using Generic class, in which we are creating two types of objects one as "int" and another "string".

We are using same class and same method, but with different data type.

Advantages of using Generics

  • Code Reusability: Allows you to write code/use library methods which are type-safe. You can use a single generic type definition for multiple purposes in the same code without any method overriding or code modification
  • Type Safety: As a result of generics being used the compiler can perform compile-time checks on code for type safety. Generic data types provide better type safety, especially in the case of collections, which is where you will most likely be using them the most from the System.Collections.Generics namespace.
  • Faster than Objects: Faster than using objects as it avoids boxing/unboxing process

Share Tweet