C# Generics β Generic Classes, Methods, and Constraints
Introduction β Why Use Generics in C#
Generics in C# allow you to write flexible, reusable, and type-safe code. Instead of writing the same logic multiple times for different data types, generics let you define a method, class, or interface with placeholders for the data types it operates on.
In this guide, youβll learn:
- What generics are and how they work
- How to create generic classes and methods
- Benefits of generics over non-generic code
- Real-world examples and best practices
Core Concept β What Are Generics?
Generics enable type parameters in classes, methods, interfaces, delegates, and more. They help you avoid redundancy and runtime casting by enforcing compile-time type checking.
Example:
List<int> numbers = new List<int>();
The List<T> is a generic class where T is replaced with int.
Generic Class β Basic Example
public class Box<T>
{
public T Value;
public void Display()
{
Console.WriteLine($"Value: {Value}");
}
}
Usage:
Box<string> nameBox = new Box<string>();
nameBox.Value = "Alice";
nameBox.Display(); // Output: Value: Alice
Generic Method Example
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
Usage:
int x = 5, y = 10;
Swap(ref x, ref y);
Console.WriteLine($"{x}, {y}"); // Output: 10, 5
Generic Constraints
You can restrict generic types using constraints to ensure they meet specific requirements.
public class Repository<T> where T : class
{
public void Save(T item)
{
// save logic
}
}
| Constraint | Description |
|---|---|
where T : class | T must be a reference type |
where T : struct | T must be a value type |
where T : new() | T must have a parameterless constructor |
where T : BaseClass | T must inherit from a class |
where T : Interface | T must implement an interface |
Tips, Pitfalls & Best Practices
Tip: Use generics to avoid repeated code blocks for multiple types.
Pitfall: You canβt use T with operators like +, - unless constrained with a specific interface or logic.
Best Practice: Use descriptive type names (TKey, TValue, TItem) in generic classes for clarity.
Use Cases of Generics
- Collections:
List<T>,Dictionary<TKey, TValue> - Repositories: Generic repositories in data access
- Utilities: Swap, Compare, Sort, etc.
- Dependency Injection: Generic services and interfaces
Summary β Recap & Next Steps
C# Generics let you build scalable and type-safe code. They’re foundational to .NET collections, reusable components, and clean architecture.
Key Takeaways:
- Generics reduce code duplication and casting
- Use
<T>to define flexible methods and classes - Apply constraints for safer, more predictable behavior
Up next: Explore C# Regular Expressions to master pattern matching in strings.
FAQ β C# Generics
What is the purpose of generics in C#?
To write reusable and type-safe code that works with any data type.
Can I use multiple type parameters in generics?
Yes, e.g., Dictionary<TKey, TValue>.
Do generics improve performance?
Yes. They avoid boxing/unboxing and reduce runtime casting.
Can I create a generic interface or delegate?
Absolutely. Generics work with interfaces and delegates too.
What are generic constraints?
They restrict the type arguments that can be used (e.g., where T : class).
Share Now :
