C# Reference ยท Classes and Object-Oriented Concepts
Generics in C#
Reference for C# generics: type parameters on classes, methods, interfaces and delegates, type inference, default(T), static members per closed type and runtime behavior.
Generics let you write a class, struct, interface, delegate or method once and use it with many types, while the compiler still checks them. You declare placeholders called type parameters in angle brackets (<T>), and the caller supplies type arguments (List<int>, Pair<string, double>). There is no casting and no boxing of value types, and mistakes such as adding a string to a List<int> are compile errors.
Unlike Java, .NET keeps generics at run time ("reified"): List<int> and List<string> are distinct types, and the JIT creates specialized code for each value type.
T Largest<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
class Name<T1, T2> { } // generic class (also struct, interface, record) delegate TResult Fn<in TArg, out TResult>(TArg a); TResult Method<TIn, TResult>(TIn x); // generic method Name<int, string> closed; // closed constructed type typeof(Name<,>) // open generic type
| Part | Description |
|---|---|
| Type parameter | A placeholder name (T, TKey) declared after the type or method name. Convention: start with T. |
| Type argument | The real type supplied by the caller. Reference types share one compiled body; each distinct value type gets its own. |
| Constraints | Optional where clauses; see generic constraints. |
| Variance | in/out on interface and delegate parameters; see covariance. |
Errors: CS0452 when the type argument violates a constraint (for example a reference-type constraint given int); CS0310 when new() is required but the type lacks a public parameterless constructor; CS0019 when you use + on an unconstrained T.
Usage notes
- Inference. For generic methods the compiler infers type arguments from the call (
Swap(1, 2)). It cannot infer from the return type alone, and it never infers type arguments of a generic class constructor call (usenew Stack<int>(); a target-typednew()also works). default(T)isnullfor reference types, zero or empty struct for value types. UseT?with aclassorstructconstraint to express nullability clearly.- Operators on
T. You cannot use+,<ornew T()on an unconstrained type. Constrain with an interface (IComparable<T>,INumber<T>) or pass a delegate. - Static members belong to each closed type.
Box<int>.CreatedandBox<string>.Createdare separate variables. - No generic attributes of arbitrary kind or generic enums. Enums cannot be generic; attributes can be generic since C# 11.
- Arrays and variance.
List<Derived>is not aList<Base>; see covariance and contravariance. - Performance.
List<int>stores ints without boxing; the oldArrayListboxed each one. Reference-type instantiations share code through a canonical form, so there is no code explosion for classes. - Reflection.
typeof(List<>)is the open definition;MakeGenericTypecloses it at run time.