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

南笙酒味 提交于 2021-01-22 08:39:23

问题


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?


回答1:


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

You also disable the warning at the top of the source file:

You also suppress warnings for the whole project.




回答2:


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.



来源:https://stackoverflow.com/questions/55984923/is-there-a-point-to-using-the-c-sharp-discard-operator-for-method-return-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!