Home > Back-end >  How to create a class that may return null?
How to create a class that may return null?

Time:12-06

I'm stuck in creating a class that may or may not return a null value.

note: I know that I can get around this by checking whether File.Exists before creating the instance (using the "alternative" block that is specific for this code), but just curious if I can...

Sample code:

using System;
using System.IO;
using System.Windows.Forms;
...

internal class FormMain : Form {
    ...
    private MyClass myClass = null;
    private readonly String fileName = "/path/to/file/file.name";
 
    public FormMain() {
        /*
        // alternative
        if (File.Exists(fileName) {
            myClass = new MyClass(fileName);
            Setup();
            DoStuff();
        }
        */
        if ((myClass = new MyClass(fileName)) != null) {
            Setup();
            DoStuff();
        }
    }
    ...
}

internal class MyClass : IDisposable {
    // list of variables (all "String" type)
    ...
    public MyClass(String fileName) {
        if (File.Exists(fileName)) {
            // load file and initialize variables
        }
        /*
        // warning here when uncommented !!!
        else {
            return null;
        }
        */
    }

    public void Dispose() {
        ...
    }
}

CodePudding user response:

Use a factory method.

internal static MyClass ConstructMyClass(String fileName) {
        if (File.Exists(fileName)) {
            // load file and initialize variables and return an instance of MyClass
        }
        /*
        // warning here when uncommented !!!
        else {
            return null;
        }
        */
    }

CodePudding user response:

A class cannot return null, a class is only the definition of an object.

If you want object creation to fail, check for certain parameters in your constructor and throw an exception.

E.g.:

class MyClass {
    MyClass(object param) {
        if (param is string) {
            throw new ArgumentException(nameof(param), "Parameter must not be string!");
        }
    }
}

Just make sure you document this behaviour so you don't shoot yourself in the foot.

Throwing here will prevent the memory from being allocated and the object from being created.

Edit: Peter's solution is more elegant, however if going that direction, I'd go for a Try-pattern:

bool TryConstructObject(out MyObject obj) {
     if (File.Exists(MyFile)) {
        obj = null;
        return false;
     }

     obj = new MyObject();
     return true;
}
  • Related