Generic methods and types
Generic methods and types
Generics let you describe a method or type using a placeholder type parameter such as T. A type argument, such as int in Pair<int>, supplies a concrete type. Instead of storing everything as object and recovering it with casts, a generic API can preserve the caller's type across inputs and outputs. A generic method has its own type parameter list after its name; an ordinary method inside a generic class is not necessarily a generic method.
An open generic type, such as Pair<> in a typeof expression, still has unfilled type parameters. A constructed type like Pair<int> has a supplied type argument; it is closed when no type parameters remain unbound. .NET retains generic type information at runtime. That does not imply a separate machine-code copy for every type argument; runtime implementation may share code.
using System;int left = 2, right = 9;Swap(ref left, ref right);Console.WriteLine($"{left} {right}");string first = "red", second = "blue";Swap(ref first, ref second);Console.WriteLine($"{first} {second}");static void Swap<T>(ref T a, ref T b){ T saved = a; a = b; b = saved;}Both arguments use the same inferred type T. The ref parameters update the caller variables; the saved local holds the old value without requiring a cast.
Expected output (reasoned, not executed):
9 2blue redCreate a reusable typed pair
using System;var counts = new Pair<int>(4, 7);var labels = new Pair<string>("pen", "pad");Console.WriteLine(counts.First + counts.Second);Console.WriteLine(labels.First);record Pair<T>(T First, T Second);The same record declaration creates differently constructed types. The caller sees integers for counts and strings for labels. Pair<T> itself need not know how to add the values.
Expected output (reasoned, not executed):
11penPreserve an absent value explicitly
using System;var found = new Lookup<int>(true, 0);var missing = new Lookup<int>(false, 0);Console.WriteLine(found.Found ? found.Value : -1);Console.WriteLine(missing.Found ? "Present" : "Missing");Console.WriteLine(typeof(Lookup<>).ContainsGenericParameters);Console.WriteLine(typeof(Lookup<int>).ContainsGenericParameters);record Lookup<T>(bool Found, T Value);The status flag distinguishes a real zero from a missing result. This tiny container is a teaching model, not an invariant-enforcing library: consumers must inspect Found before using Value. typeof inspects type metadata and is used here only to illustrate open versus closed types.
Expected output (reasoned, not executed):
0MissingTrueFalseCommon mistakes and edge cases
Without constraints, a generic method cannot assume T supports arithmetic, ordering or a particular property. An unconstrained default(T) may be zero, null or another default value, so it is not a universal missing-value indicator. Do not convert through object simply to bypass an incompatible generic type; it discards guarantees and may box values. Keep generic type parameters only when they represent meaningful type relationships.
Practice and next steps
Create record RangePair<T>(T Start, T End) and Reverse<T>(RangePair<T> pair) returning a new pair with endpoints swapped. Test integers (2,9), strings ("a","b") and a same-value pair (4,4). Ensure the original remains unchanged.
Next: Constraints and inference.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic methods and types — knowledge check
Apply the lesson concepts to the following scenarios.
What is T in `Pair<T>`?
What is int in `Pair<int>`?
Why use generic Swap<T> instead of Swap(object, object)?
What does typeof(Pair<>).ContainsGenericParameters return?
Can unconstrained T always use + on two values?