TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
var pattern is an irrefutable pattern matching construct in C# that matches any expression, including null, and assigns the evaluated result to a newly declared local variable. It relies on compiler type inference to determine the variable’s type based strictly on the compile-time (static) type of the matched expression, without performing any runtime type checking.
Mechanical Characteristics
1. Irrefutability Unlike type patterns or constant patterns, thevar pattern is irrefutable. It always evaluates to true. Because it cannot fail, it is guaranteed to execute the associated branch when used in conditional constructs like if statements or switch expressions.
2. Compile-Time Type Inference
The type of the variable introduced by the var pattern is identical to the static type of the expression being matched. It does not unbox values or downcast to derived runtime types.
var pattern successfully matches null values. This is a primary mechanical distinction between the var pattern and a type pattern using the base object type.
Variable Scoping and Definite Assignment
Variables declared via thevar pattern follow standard pattern variable scoping rules. The variable is always introduced into the enclosing scope of the pattern expression, regardless of whether the pattern matches. However, whether the variable can be read depends on the compiler’s definite assignment analysis.
Because the var pattern is irrefutable, it always succeeds, meaning the variable is unconditionally assigned and can be read in the enclosing block.
Interaction with Pattern Combinators
When used within complex pattern matching expressions, thevar pattern captures the value of the expression at the specific point of evaluation. It is frequently used inside property patterns to capture intermediate values.
and, or, not):
notpatterns: It is strictly forbidden to declare a pattern variable under anotpattern. Attempting to do so results in Compiler Error CS8773.orpatterns: A pattern variable can only be declared inside anorpattern if the exact same variable name and type are declared in all branches of theorpattern. This ensures the variable is definitively assigned regardless of which branch succeeds.andpatterns: Variables can be freely declared inandpatterns, provided they do not conflict with variables declared in other branches of the same pattern.
Master C# with Deep Grasping Methodology!Learn More





