Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using discards in C# for return methods [duplicate]

Tags:

c#

c#-7.0

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.

like image 476
Dread P. Rob the II Avatar asked Mar 02 '23 20:03

Dread P. Rob the II


1 Answers

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

like image 119
Pavel Anikhouski Avatar answered Mar 12 '23 11:03

Pavel Anikhouski