VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/generics-and-generic-classes-c-sharp/

⇱ Generics and Generic Classes in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generics and Generic Classes in C#

Last Updated : 23 Apr, 2026

In C#, Generics allow developers to design classes that can work with any data type without compromising type safety. A generic class is a class that defines one or more type parameters, which can be specified when creating an object of that class.

Why Use Generics?

  1. Type Safety: Detect type errors at compile-time instead of runtime.
  2. Code Reusability: Write a single class or method that works with multiple data types.
  3. Performance: Avoids boxing/unboxing in value types, improving execution speed.

What is a Generic Class?

A generic class is a class that takes a type parameter within angle brackets (< >) so that the class can operate on different data types while maintaining compile-time type safety. It eliminates the need to write separate classes for each data type and reduces code duplication.

Syntax

class ClassName<T>{

// members using T

}

  • T: Represents a placeholder type parameter.
  • You can specify the type when creating an object.

Generic Class Example


Output
Value: 100
Value: GeeksForGeeks

Explanation:

  • obj1 is created with int, so the generic type T is replaced by int.
  • obj2 is created with string, so the generic type T is replaced by string.

Generic Class with Multiple Type Parameters

A generic class can also take two or more type parameters, which makes it possible to store or operate on values of different data types in a single class.


Output
First: 1, Second: One

Explanation:

  • Pair<T1, T2>: A generic class is declared with two type parameters T1 and T2.
  • The constructor takes one value of type T1 and another of type T2.
  • In Main(), we create an object with int and string as type arguments, so T1 becomes int and T2 becomes string.

Key Points

  • Generic classes improve type safety by avoiding explicit type casting.
  • They are widely used in collection classes like List<T>, Dictionary<TKey, TValue>, and Queue<T>.
  • Constraints in generics ensure that only suitable types are passed as parameters.
Comment
Article Tags:
Article Tags:

Explore