C#, Resharper, "Possible 'null' assignment to entity" warning when it shouldn't be

1.9k Views Asked by At

I have a method that turns string.IsNullOrWhiteSpace(string value) into an extension method.

public static bool IsNullOrWhitespace(this string source)
{
  return string.IsNullOrWhiteSpace(source);
}

After I use this to check for null, Resharper still warns me that the variable I'm passing as a [NotNull] argument might be null.

"Possible 'null' assignment to entity marked with 'NotNull' attribute"

If I replace my use (str.IsNullOrWhiteSpace()) with the original (string.IsNullOrWhiteSpace(str)), the warning doesn't show up.

Is there a way with Resharper that I can train it to know that my extension method is a valid null checker so that this null assignment warning doesn't show up?

Note:

  1. I don't want to hide it with //resharper disable comments everwhere.
  2. I don't want to disable it entirely, as it should show up when I'm not null-checking.

Edit:

There's a property in the JetBrains.Annotations NuGet package called ContractAnnotation that does the trick.

[ContractAnnotation("source:null => true")]
public static bool IsNullOrWhitespace(this string source)
{
    return string.IsNullOrWhiteSpace(source);
}

This does the trick.

3

There are 3 best solutions below

1
On BEST ANSWER

Found it!

There's a property in the JetBrains.Annotations NuGet package called ContractAnnotation that does the trick.

[ContractAnnotation("source:null => true")]
public static bool IsNullOrWhitespace(this string source)
{
    return string.IsNullOrWhiteSpace(source);
}

This does the trick.

0
On

Except, if you want to remove the warning (ReSharper v2016.2), it should be false instead of true as shown in the answer.

[ContractAnnotation("parameterName:null => false")]

instead of

[ContractAnnotation("parameterName:null => true")]
7
On

it's because you can still call

((string)null).IsNullOrWhiteSpace()

and Resharper is concerned.

Rewrite the code as this:

(source == null) || string.IsNullOrWhiteSpace(source)

and maybe it'll stop complaining.