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

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

    I think the explanation of why exception is thrown is very clear with the answers provided here. I just wish to complement with the way I usually work with theese collections. Because, some times, I use the collection more then once and have to test if null every time. To avoid that, I do the following:

        var returnArray = DoSomething() ?? Enumerable.Empty();
    
        foreach (int i in returnArray)
        {
            // do some more stuff
        }
    

    This way we can use the collection as much as we want without fear the exception and we don't polute the code with excessive conditional statements.

    Using the null check operator ?. is also a great approach. But, in case of arrays (like the example in the question), it should be transformed into List before:

        int[] returnArray = DoSomething();
    
        returnArray?.ToList().ForEach((i) =>
        {
            // do some more stuff
        });
    

提交回复
热议问题