I frequently have code that looks something like this:
if (itm != null) { foreach (type x in itm.subItems()) { //dostuff } } //do more stuff
In situations where //do more stuff is omitted, it is very easy to avoid the extra foreach loop. By exitting scope using the appropriate command (depending on what is going on, this generally would mean a return statement or a continue statement).
This type of thing tends to result in arrow code. I currently have a few ways to deal with this:
- Use code like
itm = itm == null ? itm.subItems() : emptyArray - Allow arrow code
- Use
goto - Use evil scoping hacks (wrapping the whole thing, if statement in all, in a scope and then breaking out of it). In my opinion evil scoping hacks are basically equivalent to
gotoexcept uglier and harder to read, so I don’t consider this a valid solution. - Refactor some of the chunks into new methods. There are in fact a few cases where this probably is a good solution, but mostly it’s not appropriate since the null references are mainly error conditions from MS-functions.
Anyone care to offer a response on what approaches are considered preferable?
If you’re using C# 3, you could always write an extension method:
Then just write:
The key thing is that extension methods can be called even ‘on’ null references.
What would be nice would be a ‘null-safe dereferencing’ operator, so we could write:
Or just define an
EmptyIfNullextension method onIEnumerable<T>and use