C# Feature - Discards
Overview
Section titled βOverviewβDiscards use _ to explicitly ignore values you do not need, which keeps intent clear and avoids placeholder variables.
Introduced In
Section titled βIntroduced InβC# 7.0 (2017)
int parsedValue;bool ok = int.TryParse(text, out parsedValue);bool ok = int.TryParse(text, out _);Annotated Example
Section titled βAnnotated Exampleβvar (_, month, _) = DateTime.UtcNow;
if (value is not null and not ""){ Console.WriteLine(month);}Gotchas & Best Practices
Section titled βGotchas & Best Practicesβ- Use a real variable when the value may become meaningful later in the method.
- A discard is not a reusable variable; each
_is just an ignored target.
Related Features
Section titled βRelated FeaturesβVersion Notes
Section titled βVersion Notesβ- C# 7 introduced discards for deconstruction, pattern matching, and
outarguments.