Skip to content

CSharp Generics Intro

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Generics: Introduction and Basic Examples

This file will later be renamed from Lesson05.12.2025.md to something like CSharp-Generics-Intro.md.

Generics are a core feature in C# that let you write reusable, type-safe, and often more efficient code.

Related wiki pages:

  • General C# topics: CSharpBible.md
  • Libraries and collections: CSharpBible-Libraries.md
  • MVVM patterns with generic types: CSharpBible-MVVM-Basics.md, CSharpBible-MVVM-Standard.md

Official documentation:


1. Why generics?

Generics let you:

  • Reuse algorithms for many types (e.g. List<int>, List<string>, List<MyType>)
  • Get compile-time type safety (fewer casts, fewer runtime errors)
  • Avoid code duplication (no need for separate IntStack, StringStack, etc.)

You already use generics when you work with List<T>, Dictionary<TKey, TValue>, Task<T>, etc.


2. Generic methods

A generic method introduces type parameters in angle brackets <...>.

public static T Echo<T>(T input)
{
    return input;
}

// Usage
int i = Echo(42);          // T is inferred as int
string s = Echo("Hello"); // T is inferred as string

Explanation:

  • Echo<T> declares a generic method with type parameter T.
  • The compiler infers T from the argument type.

Another example with constraints:

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

int biggerInt = Max(5, 10);         // 10
string biggerText = Max("a", "b"); // "b"

Here where T : IComparable<T> restricts T to types that can be compared.


3. Generic classes

You can also define generic classes and interfaces.

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

    public Box(T value)
    {
        Value = value;
    }
}

// Usage
var intBox = new Box<int>(123);
var stringBox = new Box<string>("hello");

This is similar to built-in generic types like List<T>.


4. About variance (advanced)

Variance (in, out on generic type parameters) is an advanced topic mainly relevant for interfaces and delegates (e.g. IEnumerable<out T>, IComparer<in T>). For a first introduction you can safely skip it and focus on basic generic methods and classes.

For more advanced usage (interfaces, delegates, covariance/contravariance), see the official docs and cross-reference with patterns in CSharpBible-MVVM-Advanced.md.


5. Next steps

  • Read the official generics guide linked above.
  • Inspect existing generic types in this wiki (e.g. examples using List<T>, Dictionary<TKey, TValue>, Task<T> in CSharpBible-Libraries.md).
  • Try to refactor a non-generic class (e.g. a simple IntStack) into a generic version Stack<T>.

Clone this wiki locally