Code Analysis rule CA1062 behaviour
Why it thinks that I'm not checking for null condition in the first example?
Quite simply, FxCop doesn't understand that if your IsNullOrEmpty
extension method does the same thing as string.IsNullOrEmpty
. It doesn't realize that if target
is null, IsNullOrEmpty
will return true
and your method will exit. Basically I suspect it has in-built knowledge of string.IsNullOrEmpty
. Code Contracts is more likely to have success here, as I believe FxCop only performs a relatively shallow check on what your code does, compared with the deep reasoning of Code Contracts. You could decorate your IsNullOrEmpty
method with ValidatedNotNullAttribute
to inform FxCop what's going on.
public static bool IsNullOrEmpty([ValidatedNotNullAttribute] this string target)
{
return string.IsNullOrEmpty(target);
}
//The naming is important to inform FxCop
sealed class ValidatedNotNullAttribute : Attribute { }
This is just an example of where code analysis can sometimes be a little too eager to criticize. It's something I've seen with pretty much every code analysis tool I've used. Your choices are usually along the lines of:
- Change your code to work around the code analysis tool, even if it was fine before
- Suppress the rules at specific sites, after manually checking each of them
- Suppress whole rules if they frequently give false positives
- Abandon the code analysis tool entirely
You should also log a bug or feature request, of course...