📎 Webclip
Variables? We Don’t Need No Stinking Variables | C# Discards
C# 7.0 introduced discards as intentionally unused temporary values. The page shows how _ can stand in for results you do not care about, including ignored method results, out parameters, tuple elements, null-check expressions, tasks, and switch patterns.
Reading notes#
_ = 1 + 1;discards the result of an addition, and the discarded value cannot be accessed later.- When calling
int.TryParse,_can replace anoutvariable that is never used. - An expression-bodied method can return
int.TryParse(@int, out _)when only the boolean result matters. - In a method with several
outvalues, the unused ones can be written as_while keeping the one needed value. - Tuple deconstruction can ignore fields with
(_, age) = GenerateDefaultPerson();when only one element matters. - A null check can be written as
_ = message ?? throw new ArgumentNullException(nameof(message));to avoid a redundant temporary variable. _ = Task.Run(() => SayHello());discards the task result, but the page notes that exceptions are suppressed in this form.- A
switchcan usecase var _:to catch unsupported types after the more specific cases.
