Discards are write-only, unassigned dummy variables in C# represented by the underscore (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.
_) token. They instruct the compiler that a value is intentionally ignored, which prevents the allocation of memory for a named variable and suppresses compiler warnings regarding unused assignments.
Because discards do not possess a value and cannot be read, multiple discards can be utilized within the same scope without triggering identifier collision errors. The compiler infers the type of the discarded value contextually, but the discard itself is untyped.
Syntax and Mechanics
The discard pattern is integrated into several language constructs where a value must be syntactically provided or received, but the value itself is not required by the execution logic. Tuple and Object Deconstruction When deconstructing a tuple or an object, discards can be used to ignore specific elements while capturing others.out parameter, a discard can be passed inline to satisfy the method signature without declaring a local variable to hold the output.
switch statements and switch expressions, the discard acts as a wildcard or default catch-all pattern. It matches any value, including null, and is evaluated only if no preceding patterns match.
_ token without causing identifier collision errors.
Identifier Resolution Rules
The C# compiler applies specific binding rules to the_ token. If a standard variable named _ is explicitly declared and is currently in scope, standalone assignments (_ = ...) and implicitly typed out parameters (out _) will resolve to that local variable rather than acting as a discard.
However, the _ token is always treated as a discard in specific syntactic contexts, regardless of whether a local variable named _ is currently in scope. These contexts include:
- Deconstruction declarations (
var (_, _) = ...) - Pattern matching (
_ =>) - Explicitly typed
outparameters (out var _orout int _) - Lambda parameters (when multiple
_tokens are used)
_ is strongly discouraged in C# codebases.
Master C# with Deep Grasping Methodology!Learn More





