Don't report S2219 when checking for null in case of overloaded "==" and "!=" operators

I think the S2219 C# diagnostic (“Runtime type checking should be simplified”) should not be reported when doing == null or != null comparisons if the target type overloads the == or != operators, as the operators may do some “special” checks for null (whether that’s a good idea or not is another discussion…).

For example, in the case of the Unity game engine, UnityEngine.Object overloads those operators, so when you compare with null it actually checks if the object was “destroyed” by the engine or not, instead of checking whether the actual reference is null. If we have, say, an instance to a UnityEngine.Object as an interface, and we want to check if the object was destroyed, we can do:

IWhatever instance = ...;
if (instance as UnityEngine.Object == null)
...

But that triggers the S2219 diagnostic. Doing this instead:

IWhatever instance = ...;
if (instance is not UnityEngine.Object)
...

Would not have the desired effect when instance is not null but the object was destroyed.

It seems unfortunate that this would cause S2219 to stop appearing for reference types such as string and PropertyInfo that overload == and != and treat null normally.

Hi,

In the name of i-dotting, can you give the context of where you’re (not) seeing this? I.e. SonarQube Cloud? SonarQube self-hosted or SonarQube for IDE? (And if so, the flavor & version, please.)

 
Thx,
Ann

Sorry, it’s SonarQube IDE for Visual Studio, 8.30.0.15605.

1 Like

Yes, there could be exceptions for common types, or maybe it could be the other way around, show the diagnostic except when the type is known to be an issue (UnityEngine.Object is a pretty common one).

Hi,

Thanks. I’ve flagged this for the language experts.

 
Ann

1 Like