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:
itm = itm == null ? itm.subItems() : emptyArray
goto
goto
except uglier and harder to read, so I don't consider this a valid solution.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:
public static IEnumerable<SubItem> SafeSubItems(this ItemType item)
{
return item == null ? Enumerable.Empty<SubItem> : source.SubItems();
}
Then just write:
foreach (SubItem x in itm.SafeSubItems())
{
// do stuff
}
// do more stuff
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:
// Not valid C# code!
foreach (SubItem x in itm?.SubItems() ?? Enumerable.Empty<SubItem>())
{
}
Or just define an EmptyIfNull
extension method on IEnumerable<T>
and use
// Not valid C# code!
foreach (SubItem x in (itm?.SubItems()).EmptyIfNull())
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With