discard variables (_)
discard variables: – In C#, discard variables, represented by an underscore (_
), are placeholders used when you want to explicitly ignore a value or result you don’t intend to use. Discards help improve code clarity and avoid unnecessary memory allocation or variable declaration for unused values. – discard variables
How Discards Work
The _
symbol acts as a “write-only” variable. The compiler recognizes it as a discard, ensuring no memory is allocated for the value, and it cannot be read.
Common Use Cases
Ignoring Out Parameters: When using methods with out
parameters, you can discard values you don’t need:
if (int.TryParse("123", out _))
{
Console.WriteLine("Parsing successful, but result discarded.");
}
Tuple Deconstruction: In tuple assignments, you can ignore specific elements:
var (name, _, age) = ("John", "IgnoreThis", 30);
Console.WriteLine($"{name} is {age} years old.");
Pattern Matching: Discards can be used to match patterns without capturing data:
if (obj is Person _)
{
Console.WriteLine("The object is a Person, but the instance is discarded.");
}
Event Handlers: In event subscriptions where the sender or event args aren’t needed:
button.Click += (_, _) => Console.WriteLine("Button clicked!");
Switch Expressions: Discards simplify switch
expressions by ignoring unmatched cases:
string result = input switch
{
1 => "One",
_ => "Default" // Matches all other cases
};
Benefits
- Improved Readability: Signals that a value is intentionally unused.
- Performance: Prevents unnecessary memory allocation.
- Cleaner Code: Reduces clutter in methods with multiple return values.