Search code examples
c#.netusingcode-readability

How should I deal with null objects in a using block?


Given a situation like this:

using (var foo = CreateFoo()) {
    if (foo != null) {
        // do stuff
    }
}

I would like to avoid the nested if. Sadly, the obvious solution is not possible because break does not work with using:

using (var foo = CreateFoo()) {
    if (foo == null) {
        break;
    }
    // do stuff
}

Is there a pattern to still avoid the additional indentation caused by the if != null?


Solution

  • If you have sufficient control over the class returned from CreateFoo() you could just implement a Null Object and return this instead of the actual NULL value