Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a point to using the C# discard operator for method return values?

Visual Studio 2019's code analysis and code suggestions started to highlight every line of code where I call a method that returns a value but don't use that value at all and tells me to use the discard operator _.

I don't fully understand why that matters and it even seems wrong for Fluent API style code.

Is there a functional difference between the two following lines?

private int SomeMethod() => 0;
...
SomeMethod();
_ = SomeMethod();
...

Would it matter more if the return value is a reference? If not, Is there a way to globally disable this inspection?

like image 961
Ran Sagy Avatar asked May 04 '19 17:05

Ran Sagy


2 Answers

Excerpt from Microsoft Documentation:

Starting with C# 7.0, 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. Because there is only a single discard variable, and that variable may not even be allocated storage, discards can reduce memory allocations. Because they make the intent of your code clear, they enhance its readability and maintainability.

All the code analysis are done to help improve overall coding. Sometimes we write quick methods early in a project that returns a simple value. During refactor we stop using such variable for whatever reason. The code analysis is just pointing that out. And it's up to you as a developer to say, hey let me refactor the method to NOT return variable because we don't need it. It's all a matter of development style on your team.

The verify your issue, I was running VS2019 16.0.0 Preview 5.0 and the issue was there.

Following the comment made by @MartinUllrich, I upgraded to release 16.1.0 Preview 2.0. The warning have disappears. You can also disable the warning using #pragma directive

Sample with pragma directive

You also disable the warning at the top of the source file: enter image description here

You also suppress warnings for the whole project.

suppress for project

like image 157
Black Frog Avatar answered Nov 11 '22 07:11

Black Frog


Best way for this useless warning (or at least not managed well) is to suppress it in GlobalSuppressions.cs file in root of your project:

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0058")]

I have a version 16.3.0 Preview 3.0 a problem still exists.

like image 26
mojmir.novak Avatar answered Nov 11 '22 08:11

mojmir.novak