Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resharper warns about a null string (System.NullReferenceException)

Just want to be sure that I haven't been coding for too long ... But, this seems highly unlikely :

string System.NullReferenceExceptionhttp://i.imgur.com/TBjpNTX.png

I create the var, check for null, return if it is, so there's no way I can see it as being null at that point :)

Resharper bug ?

Edit:
As per Igal Tabachnik answer, he's right, I'm using the following method extension:

public static bool IsNullOrEmpty(this string target)
{
    return String.IsNullOrEmpty(target);
}

I find it much easier to read

if (some_string.IsNullOrEmpty())
  // do something here 

rather than the:

if (string.IsNullOrEmpty(some_string))
  // do something here 

Solution:
Igal Tabachnik was right. The only 2 missing pieces were:

  1. Resharper -> Options -> Code Annotations (under Code inspection group) -> turn on for solution.
  2. Give VS a couple of minutes to get refresh everything.
like image 411
Noctis Avatar asked May 01 '14 08:05

Noctis


2 Answers

Your code suggests that IsNullOrEmpty() method you're using is your own custom Extension method. The "real" IsNullOrEmpty is a static method of string.

Short answer: if you change it to

if (string.IsNullOrEmpty(input_string))
    return "...";

ReSharper will stop complaining.

Long answer: Since this is your own extension method, ReSharper has no way of knowing how the result of this method applies to your code. For this, ReSharper uses code annotations to figure out additional information about the code. One such annotation is called a Contract Annotation, and it is what ReSharper uses to figure out the result of the original string.IsNullOrEmpty() method. You can read more about it in the blog post.

Bottom line, if you want to use your own extension method, but have ReSharper understand it correctly, you have to apply the following Contract Annotation on it:

[ContractAnnotation("null=>true")]
public static bool IsNullOrEmpty(this string input)
{
    ...
}
like image 86
Igal Tabachnik Avatar answered Nov 05 '22 19:11

Igal Tabachnik


Your IsNullOrEmpty()-method seems to be an own invention since the original one is a static method of System.String and not an extension method. ReSharper isn't able to figure that one out though if you use the original one it will see that no null-values can make it past.

var str = value as string;

if (string.IsNullOrEmpty(str))
    return;

var unicorn = str.Contains("unicorn");
like image 37
Karl-Johan Sjögren Avatar answered Nov 05 '22 21:11

Karl-Johan Sjögren