Sometimes you are forced to receive a value you have no use for, such as an out argument, one element of a deconstructed tuple, or the result of a method you call only for its side effects.
Previously you had to declare a dummy variable to hold it, which clutters the code and triggers "unused variable" warnings from code analysis.
C# 7.0 introduces discards. Using _ (the underscore symbol) in these positions tells the compiler and readers that the value is intentionally ignored, and no variable is created.
Code
csharp
// Only care whether it parses
if (int.TryParse(input, out _))
Console.WriteLine("Valid number");
// Only care about one element
var (_, _, area) = GetCityInformation("Paris");
// Fire and forget, intentionally ignoring the result
_ = SendTelemetryAsync();csharp
// Only care whether it parses
int ignored;
if (int.TryParse(input, out ignored))
Console.WriteLine("Valid number");
// Only care about one element
var cityInfo = GetCityInformation("Paris");
var area = cityInfo.Item3;
// Fire and forget, intentionally ignoring the result
var ignoredTask = SendTelemetryAsync();Notes
- Discards work with
outarguments, deconstruction, pattern matching (case int _:oris var _) and standalone_ = expression;assignments - You can use
_multiple times in the same statement as no variable is ever declared - Naming a regular method parameter
_is not a discard, it is an ordinary parameter called_that can still be read- Lambda discard parameters C# 9.0 made
_a discard for lambda and anonymous method parameters when used more than once
- Lambda discard parameters C# 9.0 made
- If a variable named
_is in scope then_refers to that variable instead of being a discard