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.
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>`.
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);
}
}5 HelloThe same Box<T> class works with both int and string types safely.
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));
}
}10GetFirst<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.
