-
Notifications
You must be signed in to change notification settings - Fork 2
CSharp Generics Intro
This file will later be renamed from
Lesson05.12.2025.mdto something likeCSharp-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:
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.
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 stringExplanation:
-
Echo<T>declares a generic method with type parameterT. - The compiler infers
Tfrom 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.
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>.
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.
- 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>inCSharpBible-Libraries.md). - Try to refactor a non-generic class (e.g. a simple
IntStack) into a generic versionStack<T>.