Often I have the pieces of code that look like this:
private void OnChangeLanguageCommandExecuted(object obj)
{
pLngService.ChangeLanguage(newLcid);
}
In this case the ChangeLanguage(...) method returns a value, although that value (true for success, false for non-success) is not used. The problem is, I had no clue when looking at the code that this method was returning a value.
I did not write the method, nor have I control over it.
Therefore i'd like to globally enforce a policy where:
Each non-void returning method must be assigned a variable, e.g.
var unused = pLngService.ChangeLanguage(newLcid);
Or the discard operator should be used, to make it more explicit:
_ = pLngService.ChangeLanguage(newLcid);
I'm of course open to other suggestions, the main goal here is to make it more verbose that both a method is returning a value and that i'm choosing to discard it.
I was hoping there'd be a rule for visual studio or Resharper where i could enfore this policy by generating compiler warnings. I won't like to make this a compiler error, that seems to rigorous. I did some quick looking around but i did not find anything oob but i feel like im overlooking something.
I'm using projects in vs2017 (net4) and vs2019 (net8/netcore3.0) so something that would work in either of those setups would be great.
EDIT: I found out, literally whilst writing a roslyn code analyzer, that apperently you can configure this with https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0058
The code fixes were exactly what I was looking for:
// Original code:
System.Convert.ToInt32("35");
// After code fix for IDE0058:
// csharp_style_unused_value_expression_statement_preference = discard_variable
_ = System.Convert.ToInt32("35");
// csharp_style_unused_value_expression_statement_preference = unused_local_variable
var unused = Convert.ToInt32("35");
There is the following rule:
csharp_style_unused_value_expression_statement_preference
With options:
Option values discard_variable - Prefer to assign an unused expression to a discard
unused_local_variable - Prefer to assign an unused expression to a local variable that is never used