Discards(_) in C#
Sometimes you might have to create a variable in C# code that you will not use, like that out parameter that you don’t need. It would be nice if you don’t have to declare a variable just for the sake of it. Well, Discard solves this problem.
Discard is represented by underscore( _ ) character. You can use it in place of any temporary dummy variable and it will do the job. It will act like a variable. According to the C# Guide,
C# supports discards, which are temporary, dummy variables that are intentionally unused in application code. Discards are equivalent to unassigned variables; they do not have a value.
Here is an example use case,
Some of the popular use cases for a discard are
- Unused out variables
- When a function returns Tuple and you don’t need all it’s variables
- Other temp variables
Why should you use discards instead of temp variables?
Technically it improves code performance. Discards are not allocated storage. Using discards in a program reduces its memory consumption.
But far more importantly it makes you code clean. You don’t have to create those temp, temp1 or t, t1 variables often. The readability of the code is greatly improved.