Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReSharper "Possible NullReferenceException" wrong with FileInfo?

Tags:

c#

.net

resharper

I just started using ReSharper and I'm trying to identify why it thinks this code is wrong.

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

It highlights file.Directory as a "Possible System.NullReferenceException". I'm not sure how this is possible because the file object can never be null and I can't figure out how the DirectoryInfo object returned from the FileInfo object could ever be null.

like image 762
Jonathan Sternberg Avatar asked Sep 28 '11 14:09

Jonathan Sternberg


1 Answers

The Directory property can indeed be null. The implementation of the property is roughly

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
}
like image 156
JaredPar Avatar answered Sep 29 '22 10:09

JaredPar