开发者

ReSharper "Possible NullReferenceException" wrong with FileInfo?

开发者 https://www.devze.com 2023-04-08 20:29 出处:网络
I just started using ReSharper and I\'m trying to identify why it thinks this code is wrong. var file = new FileInfo(\"foobar\");

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.NullReferenceExc开发者_C百科eption". 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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消