Does the use of discards in C# have any performance benefit? In Visual Studio 2019, the editor suggests using discards for return type methods that are not using the returned value.
Accroding to MSDN
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. Because there is only a single discard variable, and that variable may not even be allocated storage, discards can reduce memory allocations.
As you can see, you can reduce a memory usage, because they may not be allocated. But exact behavior depends on context of your code.
The main use cases of discards are tuples, pattern matching in switch
expression
switch (obj)
{
case SomeType someTypeValue:
...
break;
case null:
...
break;
case object _:
...
break;
}
methods with out
parameters
if (int.TryParse(s, out _))
{
}
and just ignore a return value from a method _ = Task.Run(() => {...});
, like you want.
There is also a big usability benefit in terms of clean code. By using a discard _
you've indicating the return value is unused one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With