Start Coding

Topics

C# Generics

Generics in C# provide a powerful way to create reusable, type-safe code. They allow you to define classes, interfaces, and methods with placeholder types, which are specified at compile-time.

What are Generics?

Generics enable you to write flexible, reusable code that works with different data types while maintaining type safety. They were introduced in C# 2.0 to enhance code reuse and performance.

Generic Classes

A generic class uses a type parameter as a placeholder for the actual type that will be used when the class is instantiated. Here's a simple example:


public class GenericList<T>
{
    private List<T> items = new List<T>();

    public void Add(T item)
    {
        items.Add(item);
    }

    public T GetItem(int index)
    {
        return items[index];
    }
}
    

In this example, T is a type parameter that can be replaced with any type when the class is used.

Generic Methods

Generic methods allow you to define a method that can work with different types. Here's an example:


public static void Swap<T>(ref T a, ref T b)
{
    T temp = a;
    a = b;
    b = temp;
}
    

This method can swap two values of any type.

Generic Interfaces

Interfaces can also be generic, allowing you to define contracts that work with different types. For example:


public interface IRepository<T>
{
    void Add(T item);
    T Get(int id);
    IEnumerable<T> GetAll();
    void Update(T item);
    void Delete(int id);
}
    

Constraints

Generics can use constraints to restrict the types that can be used as type arguments. This allows you to specify certain characteristics that the type must have.


public class MathOperations<T> where T : struct, IComparable<T>
{
    public T Max(T a, T b)
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}
    

Benefits of Generics

  • Type Safety: Catch type errors at compile-time rather than runtime.
  • Code Reusability: Write code that works with multiple types.
  • Performance: Avoid boxing and unboxing operations for value types.
  • Readability: Make code intentions clearer and reduce the need for type casting.

Related Concepts

To further enhance your understanding of C# generics, explore these related topics:

Mastering generics is crucial for writing efficient, flexible C# code. They form the foundation for many advanced C# features and are extensively used in the .NET Framework.