Skip to content

C# Generics

Overview

Generics allow you to write type-safe, reusable code that works with different data types.

Generic Classes

csharp
public class GenericList<T>
{
    private List<T> _items = new List<T>();
    
    public void Add(T item) => _items.Add(item);
    public T Get(int index) => _items[index];
    public int Count => _items.Count;
    
    public void DisplayAll()
    {
        foreach (T item in _items)
        {
            Console.WriteLine(item);
        }
    }
}

// Usage
GenericList<int> intList = new GenericList<int>();
GenericList<string> stringList = new GenericList<string>();

Generic Methods

csharp
public class MathHelper
{
    public static T Max<T>(T a, T b) where T : IComparable<T>
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
    
    public static void Swap<T>(ref T a, ref T b)
    {
        T temp = a;
        a = b;
        b = temp;
    }
}

Generic Constraints

csharp
public class DataProcessor<T> where T : class
{
    public void Process(T item) => Console.WriteLine(item?.ToString());
}

public class NumericProcessor<T> where T : struct
{
    public T Add(T a, T b) => (dynamic)a + (dynamic)b;
}

public class Repository<T> where T : new()
{
    public T Create() => new T();
}

Practical Examples

csharp
public class Stack<T>
{
    private List<T> _items = new List<T>();
    
    public void Push(T item) => _items.Add(item);
    public T Pop()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("Stack is empty");
        
        T item = _items[_items.Count - 1];
        _items.RemoveAt(_items.Count - 1);
        return item;
    }
    
    public int Count => _items.Count;
}

Content is for learning and research only.