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
}
精彩评论