C# ยท Chapter 44 of 46

C# Generics

Generics let you write classes and methods that work with any data type while still being type-safe, using placeholder type parameters like T. Instead of writing separate versions of a class for int, string, etc., you write one generic version.

List<T> and Dictionary<TKey, TValue> are examples of generic classes already built into .NET. You can also create your own generic classes and methods.

Syntax
class Name<T> {
  public T Value;
}
static T Method<T>(T param) { }

Generic methods

A generic method uses a type parameter in angle brackets, like `static T GetFirst<T>(T[] items)`, allowing it to work with any array type while keeping type safety.

Generic classes

A generic class, like `class Box<T> { public T Value; }`, can store any type of data specified when the class is used, such as `Box<int>` or `Box<string>`.

Example 1 (csharp)
using System;

class Box<T> {
  public T Value;
}

class Program {
  static void Main() {
    Box<int> intBox = new Box<int> { Value = 5 };
    Box<string> strBox = new Box<string> { Value = "Hello" };
    Console.WriteLine(intBox.Value + " " + strBox.Value);
  }
}
Output
5 Hello

The same Box<T> class works with both int and string types safely.

Example 2 (csharp)
using System;

class Program {
  static T GetFirst<T>(T[] items) {
    return items[0];
  }

  static void Main() {
    int[] numbers = { 10, 20, 30 };
    Console.WriteLine(GetFirst(numbers));
  }
}
Output
10

GetFirst<T> works generically with any array type, here inferred as int.

Key points

  • Generics let one class or method work with many data types safely.
  • Type parameters like T are placeholders specified when the type is used.
  • List<T> and Dictionary<TKey, TValue> are common generic types in .NET.
  • Generics avoid code duplication while keeping compile-time type safety.
๐Ÿ’ก Note: Generics catch type mismatches at compile time, unlike using a non-generic object type which risks runtime errors.

๐Ÿ“ Quick Quiz

1. What is a common letter used as a generic type parameter?

2. Which built-in .NET type is a generic collection?

3. What is a key benefit of generics?