0
0
CsharpHow-ToBeginner · 3 min read

How to Use Discard Pattern in C# for Ignoring Values

In C#, the discard pattern uses the underscore _ to ignore values you don't need in assignments, deconstruction, or pattern matching. It tells the compiler to skip storing or using that value without declaring a variable.
📐

Syntax

The discard pattern uses a single underscore _ as a placeholder to ignore values. It can be used in:

  • Variable assignments
  • Deconstruction of tuples or objects
  • Pattern matching in switch or is expressions

Using _ means you do not create a variable or store the value.

csharp
var (_, y) = (1, 2); // discard first value, keep second
if (obj is Person(_, var name)) { /* discard first property */ }
💻

Example

This example shows how to use the discard pattern to ignore values when deconstructing a tuple and in a switch expression.

csharp
using System;

class Program
{
    static void Main()
    {
        var point = (x: 5, y: 10);

        // Discard the x value, keep y
        var (_, y) = point;
        Console.WriteLine($"Y value is {y}");

        object shape = (3, 4);

        switch (shape)
        {
            case (int _, int b):
                Console.WriteLine($"Second value is {b}");
                break;
            default:
                Console.WriteLine("Unknown shape");
                break;
        }
    }
}
Output
Y value is 10 Second value is 4
⚠️

Common Pitfalls

Common mistakes when using the discard pattern include:

  • Thinking _ stores a value — it does not create a variable.
  • Using _ multiple times in the same scope as if they are different variables (they are all the same discard).
  • Trying to use _ as a variable name elsewhere (it is reserved for discard in patterns).

Remember, _ means "ignore this value" and you cannot access it later.

csharp
/* Wrong: Trying to use discard as variable */
// int _ = 5; // Error: '_' cannot be used as a variable name in this context

/* Right: Use discard to ignore value */
var (_, y) = (1, 2); // Only y is stored
📊

Quick Reference

UsageDescriptionExample
Discard in tuple deconstructionIgnore unwanted tuple elementsvar (_, y) = (1, 2);
Discard in pattern matchingIgnore parts of a patternif (obj is Person(_, var name)) { }
Discard in switch casesIgnore parts of matched valuecase (int _, int b):
Discard in out parametersIgnore out parameter valueif (int.TryParse(s, out _)) { }

Key Takeaways

Use underscore (_) to ignore values you don't need in assignments or patterns.
Discard pattern does not create a variable or store the ignored value.
You cannot access or reuse the discarded value later in code.
Avoid using _ as a variable name since it is reserved for discard.
Discard pattern works well in tuple deconstruction, pattern matching, and out parameters.