Why does .NET foreach loop throw NullRefException when collection is null?

前端 未结 11 1873
长发绾君心
长发绾君心 2020-11-28 20:34

So I frequently run into this situation... where Do.Something(...) returns a null collection, like so:

int[] returnArray = Do.Something(...);
         


        
11条回答
  •  孤城傲影
    2020-11-28 21:30

    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
    }
    

提交回复
热议问题