Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio - is there a way to generate a warning if a return value is not checked?

We have an in-house API written in C# where many of the methods have return values, typically bool's or ints, which sometimes the callers ignore. The return values are there for a reason, e.g., to indicate a problem or result of some kind, so we want to encourage the callers to actually check the result rather than just blithely assuming the method worked as expected, only to have things go bad farther downstream.

Is there a way to use the Visual Studio compiler to enforce checking return values by flagging calls, using a warning or error, when a caller fails to check the return value of a non-void method?

like image 450
user316117 Avatar asked Sep 18 '15 20:09

user316117


People also ask

How do I enable warnings in Visual Studio?

If you want to turn it on (or off) in the project setting, you have to go to: Configuration Properties -> C/C++ -> Command Line and then under Additional Options you can enter: /w3#### to set your warning to level 3, and thus enable it; or you can enter /wd#### to disable a warning.

How do I see errors in Visual Studio code?

You can click on the summary or press Ctrl+Shift+M to display the PROBLEMS panel with a list of all current errors. If you open a file that has errors or warnings, they will be rendered inline with the text and in the overview ruler.


2 Answers

If you want to encourage better practices, use exceptions. That'll at least make them aware something is happening if they simply neglected to do anything. If they bury the exception, they bury it. But it requires an active decision to do so.

Basically any time your code can go "I'm at a point where there's a problem and the solution is either absent or ambiguous" is when to throw.

Besides throwing exceptions, when you return control back to the caller, there's nothing programmatically you can do to enforce what they do afterwards.

like image 61
A.Konzel Avatar answered Oct 13 '22 08:10

A.Konzel


There already is an compiler-warning for this, [MSDN][1]

[1]: https://msdn.microsoft.com/en-us/library/ms182273.aspx is you use FX cop

like image 32
Luc Avatar answered Oct 13 '22 08:10

Luc