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

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

    Because a null collection is not the same thing as an empty collection. An empty collection is a collection object with no elements; a null collection is a nonexistent object.

    Here's something to try: Declare two collections of any sort. Initialize one normally so that it's empty, and assign the other the value null. Then try adding an object to both collections and see what happens.

提交回复
热议问题