π 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 :
