Glossary / Type inference
Type inference
Type inference is the compiler's process for determining types from expressions, assignments, arguments, and generic use without requiring every type to be written explicitly. C# uses inference for var locals, generic method type arguments, lambda parameter and return contexts, target-typed expressions, and query expressions while preserving static type checking.
Inference contexts
For var x = expression, the inferred type is based on the initializer's compile-time type. Generic method inference uses argument types and parameter shapes to determine type parameters; inference may fail or choose a wider common type when inputs differ. Target typing flows an expected type into expressions such as lambdas, collection expressions, and new().
static T Identity<T>(T value) => value;
var number = Identity(42); // T inferred as int
Inference does not inspect runtime values to pick a new type later, and it does not make C# dynamically typed. Nullable flow state is related but distinct: a variable can have static type string? with current state known not-null after a check. Literal inference, numeric conversions, overload resolution, and tuple names can affect results in ways that deserve attention in complex APIs.
API design and diagnostics
Generic APIs with many competing overloads can produce confusing inference or ambiguity. Use explicit type arguments or casts when they clarify intent; redesign overloads when callers must repeatedly fight inference. Compiler error messages and IDE inferred-type display are useful debugging tools. Public APIs should favor predictable inference and avoid type signatures whose behavior changes dramatically from small argument edits.
Interview questions
- Does type inference mean no types exist? No; the compiler computes static types and enforces them.
- What is generic method inference? Choosing type arguments from call argument and parameter relationships.
- How does target typing differ? An expected type helps determine the type of an expression.
- Static type vs null state? Static type is declared/inferred type; null state is flow analysis about current possibility of null.
- How fix ambiguous inference? Supply explicit generic arguments/casts or simplify competing overloads.