skip to content

In C#, when is `_` a discard and when is it an ordinary variable, as in `_ = SendAuditAsync();` versus `var _ = SendAuditAsync();`?

level: middleimportance: nice to knowfreq 30%

answer

  1. an identifier first, a discard second
  2. assignment versus declaration
  3. an existing _ in scope wins
  4. one lambda parameter, or two
  5. out _ and warning CS4014

basics

~20 s

In C#, _ is a discard only when no variable named _ is in scope: _ = expr;, out _, or several _ lambda parameters. var _ = expr; declares an ordinary local named _ instead.

solid answer

~50 s

`_` is a valid identifier, and the compiler treats it as a discard only when no variable named `_` is in scope. Discards appear as `_ = expr;` (a result ignored on purpose, which also silences CS4014 for an unawaited task), `out _` or `out var _` for unwanted out arguments, and lambdas with two or more `_` parameters (C# 9). A declaration statement `var _ = SendAuditAsync();` is not a discard: it declares an ordinary local named `_` whose scope is the whole block, so an earlier `out _` in that block now refers to it and fails with CS0841, and a later `_ = ...` assigns it. A lambda with a single `_` parameter also has a real, readable parameter: `_ => _ * 2` compiles. Write `_ = expr;` to ignore a result.

code

csharp · 21 lines
csharp
using System;
using System.Threading.Tasks;

await ImportAsync(["1200", "n/a", "950"]);

static async Task ImportAsync(string[] rows)
{
    foreach (var row in rows)
    {
        if (!int.TryParse(row, out _))
            Console.WriteLine($"skipped {row}");
    }
    _ = SendAuditAsync(rows.Length);
    await Task.Delay(100);
}

static async Task SendAuditAsync(int count)
{
    await Task.Yield();
    Console.WriteLine($"audit: {count} rows");
}

go deeper

for a junior

Recall the three common discard forms: _ = expr;, out _ and lambdas with several _ parameters, and that reading a discard does not compile.

for a middle

Explain that _ is an identifier first, that var _ = expr; declares a local whose scope is the whole block, and why a single _ lambda parameter is readable.

for a senior

Catch the var _ trap in review and the habit of discarding tasks just to silence CS4014; ask what happens when the discarded task fails.

for a principal

Make the convention explicit: assignment-form discards only, and every discarded task justified by how its failures are observed.

## A discard is a placeholder you cannot read A **discard** (C# 7) is the token `_` used where C# requires a variable but you intend to ignore the value. You cannot read a discard: with no variable named `_` in scope, `Console.WriteLine(_)` is **CS0103** ("The name '_' does not exist in the current context"). In some situations the compiler can avoid allocating storage for one. Discards make intent visible to reviewers and analyzers: this value is ignored on purpose. ## Where `_` is a discard - **Assignment**: `_ = SendAuditAsync(rows.Length);` evaluates the call and ignores its result. Inside an `async` method this also silences warning **CS4014**, which the compiler reports for a task-returning call that is neither awaited nor assigned. - **`out` arguments**: `int.TryParse(row, out _)` or `out var _` when only the `bool` result matters; several `out _` arguments in one call are fine. - **Lambda parameters**: since **C# 9**, when a lambda has **two or more** parameters named `_`, they are all discards, as in `(_, _) => 0`. - **Deconstruction and patterns** use the same token; those uses are covered with tuples and with pattern matching. ## When `_` is an ordinary variable `_` is a valid identifier, and the compiler treats it as a discard only when it finds no variable named `_` in scope. Several forms create such a variable: | Code | What `_` is | |---|---| | `_ = expr;` with no `_` in scope | a discard | | `var _ = expr;` as a declaration statement | an ordinary local named `_` | | `int _ = 5;` | an ordinary local named `_` | | `_ => _ * 2`, a lambda with a single `_` parameter | an ordinary parameter, readable in the body | | `(_, _) => 0` | two discards | The C# 9 design keeps a single `_` lambda parameter as a regular parameter for backward compatibility, which is why `Func<int, int> twice = _ => _ * 2;` compiles and `twice(21)` returns 42. ## The `var _` trap in a payroll import A developer wants to ignore an audit task and writes a declaration instead of an assignment: ```csharp foreach (var row in rows) { if (!int.TryParse(row, out _)) Console.WriteLine($"skipped {row}"); } var _ = SendAuditAsync(rows.Length); ``` The declaration makes `_` a local of type `Task` whose scope is the **whole block**, including the loop above it. `out _` therefore stops meaning "discard": it names that local before its declaration, and the SDK reports **CS0841** ("Cannot use local variable '_' before it is declared"). Had the declaration come first, `out _` would have been a type error instead (a `Task` local cannot receive an `out int`), and a later `_ = SendOtherAsync();` would assign that local rather than discard anything. The fix is the assignment form, `_ = SendAuditAsync(rows.Length);`. ## Discarding a task is not a safety mechanism `_ = SendAuditAsync(...)` documents that the result is ignored; it does not wait for the task, cancel it or observe its exceptions. If the task fails, this method never sees the exception. Whether ignoring a task is acceptable at all is a question for the material on task combinators and failures; the discard only records the decision. ## Review checklist 1. Use `_ = expr;`, never `var _ = expr;`, to ignore a result. 2. Before relying on `_` as a discard, check that no local, parameter or single lambda parameter named `_` is in scope. 3. Use `out _` instead of a dummy variable when only a `Try` method's `bool` matters. 4. Treat a discarded task as a decision to review, not as a fix for warning CS4014.

  • Does `_ = SendAuditAsync();` make it safe to fire and forget a task?
    No. The discard states that the result is ignored and silences CS4014, but the task still runs unobserved: nothing waits for it, nothing cancels it, and an exception it throws never reaches the method that started it. Whether that is acceptable, and how to observe failures, is a design decision about tasks, not something the discard decides.
  • Why does `Func<int, int> twice = _ => _ * 2;` compile if `_` is a discard?
    A lambda with a single parameter named `_` keeps it as an ordinary parameter, for backward compatibility with code written before C# 9 introduced discard parameters. Only when two or more parameters are named `_`, as in `(_, _) => 0`, do they become discards. So `twice(21)` returns 42.

  • var _ = expr; discards the value just like _ = expr;
  • _ is a reserved keyword and can never name a variable
  • A lone _ lambda parameter cannot be read in the body
  • Assigning a task to _ cancels it
  • A discard's value can be read back later through _
  • out _ always discards, whatever else is in scope