9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 41 views

πŸš€ 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
    }
}
ConstraintDescription
where T : classT must be a reference type
where T : structT must be a value type
where T : new()T must have a parameterless constructor
where T : BaseClassT must inherit from a class
where T : InterfaceT 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸš€ C# Generics

Or Copy Link

CONTENTS
Scroll to Top