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

前端 未结 11 1866
长发绾君心
长发绾君心 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:26

    A foreach loop calls the GetEnumerator method.
    If the collection is null, this method call results in a NullReferenceException.

    It is bad practice to return a null collection; your methods should return an empty collection instead.

提交回复
热议问题