Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Object Pattern for FileInfo

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?

like image 301
Micha Avatar asked Mar 22 '23 11:03

Micha


1 Answers

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.

like image 98
Miguel Angelo Avatar answered Apr 05 '23 17:04

Miguel Angelo