Skip to content

Discards C# 7.0correctnessreadability

Signal that values are intentionally being ignored.

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 out arguments, deconstruction, pattern matching (case int _: or is 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
  • If a variable named _ is in scope then _ refers to that variable instead of being a discard

More information ​

Powered by Intracia