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

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

    It is being answer long back but i have tried to do this in the following way to just avoid null pointer exception and may be useful for someone using C# null check operator ?.

         //fragments is a list which can be null
         fragments?.ForEach((obj) =>
            {
                //do something with obj
            });
    

提交回复
热议问题