- Operating system: Windows 10 Pro 22H2
- Visual Studio version: 18.0.2
- SonarQube for Visual Studio plugin version: 9.1.0.15828
- Programming language you’re coding in: C#
- Is connected mode used: No
I get a false positive for S1854 in this code when setting myClassLocal = null in the catch block, even though the variable is used in the finally block after throwing. It seems that the null-conditional operator somehow causes it, because commenting out the line myClassLocal?.SetNumber(123); makes the report go away.
using static System.Console;
namespace Test;
internal static class Program
{
class MyClass
{
public int Number { get; private set; }
public void SetNumber(int value) => Number = value;
}
static MyClass myClassField;
static void Main()
{
try
{
Do();
}
catch
{
// ...
}
WriteLine(myClassField.Number);
ReadLine();
}
static void Do()
{
MyClass myClassLocal = new();
myClassField = myClassLocal;
try
{
// ...
}
catch
{
myClassLocal.SetNumber(0);
myClassLocal = null; // S1854 false positive
throw;
}
finally
{
// Commenting this single line removes the S1854 report:
myClassLocal?.SetNumber(123);
if (myClassLocal != null)
{
myClassLocal.SetNumber(123);
}
}
}
}