Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 844
mafu Avatar asked Dec 13 '22 09:12

mafu


1 Answers

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

like image 60
yas4891 Avatar answered Dec 14 '22 23:12

yas4891