ReSharper "Possible NullReferenceException" is incorrect in FileInfo?

I just started using ReSharper, and I'm trying to determine why it considers this code to be wrong.

var file = new FileInfo("foobar"); return file.Directory.FullName; 

It highlights file.Directory as "Possible System.NullReferenceException". I am not sure how this is possible because the file object can never be null, and I cannot understand how the DirectoryInfo object returned from the FileInfo object can ever be null.

+7
source share
2 answers

The Directory property may indeed be null . Property implementation is approximately equal

 public DirectoryInfo Directory { get { string directoryName = this.DirectoryName; if (directoryName == null) { return null; } return new DirectoryInfo(directoryName); } } 

It can definitely return null . Here is a concrete example

 var x = new FileInfo(@"c:\"); if (x.Directory == null) { Console.WriteLine("Directory is null"); // Will print } 
+11
source

Take a look at the code. Each point represents a drilling of another object. Since you stated that “a file object can never be null” (right), what other object can be empty in this equation. Hint: This is not a full name.

0
source

All Articles