C# Discard Variable _ — Complete Guide
In this tutorial, you'll learn about C# Discard Variable _. We cover key concepts, practical examples, and best practices.
You call a method that returns a tuple but you only need one value. Or you have an out parameter you do not use. You declare a variable you never reference, generating a warning. The discard _ tells the compiler you intentionally ignore that value.
Wrong
var (result, _unused) = ParseInput(input);
Console.WriteLine(result); // _unused declared but never used
Output: Warning CS0168: The variable _unused is declared but never used.
Or worse, you name it unused and later accidentally reference it.
Right
var (result, _) = ParseInput(input);
Console.WriteLine(result); // Clean — no warning
Output: result printed. The second value is discarded.
Discards work with:
- Tuples:
var (x, _, _) = GetTuple() - Out parameters:
TryParse(input, out _) - Switch expressions:
_ => default - Pattern matching:
if (obj is int _) // true if int, value ignored - Deconstruction:
var _ = GetValue() // discard result
Multiple discards in the same scope do not conflict — each _ is independent.
Prevention
- Use
_for out parameters you do not need:int.TryParse(s, out _). - Use
_in deconstruction to skip positions:(first, _, last). - Use
_as the default arm in switch expressions. - Use
_in lambda parameters when the parameter is unused:(_, _) => result. - Use
_withTask.WhenAllwhen you only care about completion:await Task.WhenAll(t1, t2); // discard?. - Never name a regular variable
_— it conflicts with the discard meaning.
Common Mistakes with discard variable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Discards are used across DodaTech's codebase — from Doda Browser's IPC handlers to Durga Antivirus Pro's log processing. For more C# tips, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro