When building applications in C#, you often face situations where the same logic is repeated for different data types. Writing separate code for each type not only leads to duplication but also makes your code harder to maintain. This is where Generics come into play.
Generics allow you to create classes, methods, interfaces, and delegates with a placeholder for the data type, which is specified when you use them. They provide a way to design reusable and type-safe components without sacrificing performance.
Why Use Generics?
Generics are a powerful feature in C# because they provide several key advantages:
- Type Safety – Catch errors at compile time rather than at runtime.
- Reusability – Write code once and apply it to multiple data types.
- Performance – Eliminate unnecessary boxing/unboxing operations.
- Cleaner Code – Reduce duplication and make your code easier to read.
Example 1: Generic Class
public class Box<T>
{
public T Value { get; set; }
public Box(T value)
{
Value = value;
}
public void Display()
{
Console.WriteLine($"Value: {Value}");
}
}
Usage:
Box<int> intBox = new Box<int>(123);
Box<string> strBox = new Box<string>("Hello Generics");
intBox.Display(); // Output: Value: 123
strBox.Display(); // Output: Value: Hello Generics
Here, the same Box<T> class can store integers, strings, or any other type.
Example 2: Generic Method
public class Utilities
{
public static void PrintItem<T>(T item)
{
Console.WriteLine(item);
}
}
Usage:
Utilities.PrintItem(100); // int
Utilities.PrintItem("Generics!"); // string
Utilities.PrintItem(3.14); // double
The method works with any data type while maintaining type safety.
Example 3: Constraints on Generics
Sometimes, you may want to restrict the kinds of types that can be used in your generic class or method. This is done with constraints:
public class Repository<T> where T : class, new()
{
public T CreateInstance()
{
return new T();
}
}
Common Constraints:
where T : class→ must be a reference typewhere T : struct→ must be a value typewhere T : new()→ must have a parameterless constructorwhere T : BaseClass→ must inherit fromBaseClasswhere T : IInterface→ must implementIInterface
Example 4: Built-in Generics in C#
Generics are used extensively in the .NET Framework, especially in collections:
List<int> numbers = new List<int>() { 1, 2, 3 };
Dictionary<int, string> users = new Dictionary<int, string>()
{
{1, "Alice"},
{2, "Bob"}
};
Here, List<T> and Dictionary<TKey, TValue> are examples of generic classes.
Example 5: Generic Interface
public interface IRepository<T>
{
void Add(T item);
T Get(int id);
}
This interface can be implemented with different types, making it flexible and reusable.
Conclusion
Generics in C# are a powerful way to write code that is reusable, type-safe, and efficient. Whether you are working with collections, repositories, or utility methods, generics allow you to avoid repetitive code while keeping performance high.
If you haven’t used generics in your projects yet, now is the perfect time to explore them — you’ll quickly see how they simplify your codebase and make it more maintainable.
