I find myself writing the following over and over:
if (myEnumerable != null) {
foreach (var element in myEnumerable) {
DoSomething(element);
}
}
It’s tedious to check for NULL every time I want to enumerate, is there a better way? For instance, is there a way to override the enumerator to return “Enumerable.Empty” instead of NULL?
Well, ideally design your code so that it can’t be null. Alternatively, create an extension method:
Then:
This is much the same as Darin’s approach, but moves the null coalescing operator into an extension method.