So I frequently run into this situation... where Do.Something(...)
returns a null collection, like so:
int[] returnArray = Do.Something(...);
>
There is a big difference between an empty collection and a null reference to a collection.
When you use foreach
, internally, this is calling the IEnumerable's GetEnumerator() method. When the reference is null, this will raise this exception.
However, it is perfectly valid to have an empty IEnumerable
or IEnumerable
. In this case, foreach will not "iterate" over anything (since the collection is empty), but it will also not throw, since this is a perfectly valid scenario.
Edit:
Personally, if you need to work around this, I'd recommend an extension method:
public static IEnumerable AsNotNull(this IEnumerable original)
{
return original ?? Enumerable.Empty();
}
You can then just call:
foreach (int i in returnArray.AsNotNull())
{
// do some more stuff
}