Null Object Pattern for FileInfo
.net, c#, design-patterns, file, fileinfo
Solution
You could use the `??` operator to use a default `FileInfo` where needed, with a static variable somewhere representing what is the default fileinfo:
public void MyMethod(FileInfo fi)
{
// use default fileinfo if null is passed to this method
fi = fi ?? DefaultFileInfo.Value;
// method code...
// do something with the fileinfo, it is not null for sure now.
}
The default file info class:
public static class DefaultFileInfo
{
public static readonly FileInfo Value = new FileInfo("null");
}
If you what to make the default file readable, of course you would need to specify a valid file name.
Problem
I have a method which returns a `FileInfo`-object. After calling the method `fooFile.FullName` is called. All fine but there is a case where `FileInfo` can be `null`, but I don't want (ugly) null-checks where the method is called. What I neet is some kind of null-FileInfo (Null-Object-Pattern). It would be enough when calling `fooFile.FullName` returns a empty string. Unfortunately `new FileInfo(string.Empty)` doesn't work. Searching SO bring this java-question, but answers didn't help me. Is there a way to use `FileInfo` in combination with Null-Object-Pattern?