S1854 False Positive

Please provide

  • Operating system: Windows 11
  • Visual Studio version: 2022 17.11.5
  • SonarLint plugin version: 8.6.0.10679
  • Programming language you’re coding in: C#
  • Is connected mode used: Yes
    • Connected to SonarCloud or SonarQube (and which version):
      SonarQube Enterprise Edition v9.9.7 (build 96285)

And a thorough description of the problem / question:

In the following code it’s considered best practice to set your object to NULL after releasing it to expedite garbage collection, but this assignment to null is triggering a S1854 warning.

        if (worksheet != null)
        {
          Marshal.ReleaseComObject(worksheet);
          worksheet = null;
        }

Hi @Eos, welcome to our community!
Can you provide some documentation explaining that setting the object to null after releasing is considered best practice? Thanks

It’s not exactly documented in a white paper somewhere but you can see it applied in Microsoft examples with COM automation objects such as this one here -

' Release all existing references to appointment items, 
 
 ' including the appointment collection, an exception, occurrence, 
 
 ' or any other appointment. 
 
 Debug.Print "REFRESH ITEM COLLECTION" 
 
 Set oItems = Nothing 
 
 Set oItemNew = Nothing 
 
 Set oEx = Nothing 
 
 Set oEx2 = Nothing 
 
 Set oOccurrence = Nothing 
 
 Set oItemOriginal = Nothing 
 
 Set rPattern = Nothing 

And various blogs, forums and experts have been arguing and debating it for 20 years now -

we suggest doing two things simultaneously: release the variable and nullify it.

Gemini says;

ChatGPT says;

GitHub CoPilot, ChatGPT and Gemini all agree this is in fact the convention to the point CoPilot insists it be there and Sonar insists it not :slight_smile:

Thank you for the insight, we’ll definitely look into it and adapt the rule if need be.
In the meantime, you can either Accept the issue or mark it as False Positive.