The declaration pattern in C# is a pattern matching construct that checks whether a runtime value is compatible with a specified type and, upon a successful match, binds the converted result to a newly declared local variable. It combines type testing and safe casting into a single operation.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Syntax
The syntax of the declaration pattern itself consists strictly of a type and a designation (a variable name or a discard):Type: The target type to match against.variableName: The identifier for the newly declared pattern variable. A discard (_) can be used if the bound value is not needed.
Contexts of Use
Because patterns do not evaluate themselves, the declaration pattern must be hosted within a pattern-matching construct. The primary contexts include:- The
isOperator: Evaluates the pattern and yields a boolean result. switchStatements: Evaluates the pattern to determine branch execution.switchExpressions: Evaluates the pattern to return a corresponding expression arm.
Execution Mechanics
When an enclosing construct evaluates an input value against a declaration pattern, the runtime performs the following sequence:- Type Testing: The runtime checks if the input value is of type
Type(or derived fromType). - Null Checking: If the input value is
null, the pattern match fails, even ifTypeis a reference type or a nullable value type. - Binding: If the type test succeeds, the runtime casts the value to
Typeand assigns it tovariableName. - Construct Resolution: The pattern reports match success or failure to the enclosing construct. The construct then dictates the control flow (e.g., the
isoperator yieldstrue, or aswitchroutes to a specificcase). The pattern itself does not yield a boolean value.
Scope and Definite Assignment
The declaration pattern introduces a pattern variable into the enclosing lexical scope. However, C# enforces flow-dependent definite assignment rules. The variable is only accessible and considered initialized in code paths where the compiler can guarantee the pattern match succeeded.Type Handling Characteristics
- Reference Types: Performs standard polymorphic type checking. The match succeeds if the input’s runtime type is exactly the target type or derives from it.
- Value Types and Unboxing: The pattern handles unboxing automatically. If the input is a boxed
int(e.g., stored in anobjectreference), evaluating it against the patternint iwill successfully unbox the value, allocateion the stack, and assign the unboxed value to it. - Nullable Value Types: Matching a nullable value type expression against its underlying non-nullable type (e.g., evaluating an
int?input against the patternint i) successfully extracts the underlying value, provided the input is not null.
Master C# with Deep Grasping Methodology!Learn More





