C# Generics Explained: Type-Safe Reusable Code

Generics let you write reusable code while keeping compile-time type safety. They are used throughout .NET, from List<T> to dictionaries and many framework APIs.


๐Ÿงฉ What Is a Generic Type?

A generic type uses a type parameter instead of hard-coding a specific data type.

public class Box<T>
{
    public T Value { get; set; }
}

var numberBox = new Box<int> { Value = 10 };
var textBox = new Box<string> { Value = "Hello" };

The same class works with different types without casts.


โšก Generic Methods

Methods can also define their own type parameters.

static T First<T>(T a, T b)
{
    return a;
}

int number = First(10, 20);
string text = First("A", "B");

The compiler can infer the type argument from the values passed to the method.


๐Ÿ”’ Generic Constraints

Constraints tell the compiler what a type parameter must support.

static T Create<T>() where T : new()
{
    return new T();
}

Other common constraints include class, struct, a base class, or an interface.


๐Ÿง  Why Use Generics?


๐Ÿ“ฆ Generics in .NET Collections

Common generic collections include List<T>, Dictionary<TKey,TValue>, HashSet<T>, Queue<T>, and Stack<T>.


๐Ÿšซ A Common Mistake

Do not make everything generic simply because you can. A generic abstraction should represent a real reusable relationship between types.


๐Ÿงช Generic Interface Example

public interface IRepository<T>
{
    T GetById(int id);
    void Add(T item);
}

This pattern can provide a strongly typed contract for different domain entities.


๐ŸŽฏ Key Takeaway

Generics allow C# code to be reusable without giving up type safety. Learn them well and many .NET APIs become much easier to understand.

Continue with ๐Ÿ’ป C# Tutorials.

๐Ÿค– AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

๐Ÿ’ฌ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.