S3900: “Arguments of public methods should be validated against null” currently fires for the this parameter in C# extension methods:
public void LogCustomError(this ILogger logger, string errorMessage)
{
// Triggers S3900 for `logger`
logger.LogError(errorMessage);
}
This seems questionable, I think, because if someone calls an extension method on a null variable, then we’d actually expect to get a NullReferenceException:
ILogger myLogger = null;
// We'd expect this to throw a NullReferenceException, even though LogCustomError() is an extension method.
myLogger.LogCustomError("encountered error");
I’d like to request that SonarQube also have some way to disable S3900 warnings for extension methods
(Alternatively, perhaps the best way for us to handle this is to activate CA1062 warnings and disable S3900 warnings, since they’re essentially duplicates?)
This seems questionable, I think, because if someone calls an extension method on a null variable, then we’d actually expect to get a NullReferenceException (…)
Do we? I would strongly disagree. Extension methods are (nice) syntactic sugar. I would argue that you what to guard and throw an ArgumentNullException instead.
I my opinion it’s better to handle the “this” parameter in a similar way to be able to “fail fast”. You could also manually check for null and throw a NullReferenceException.