Why is Throwing NullRefrenceException the prefered behaviour when foreach gets a NULL item?

Viewed 54

I understand that the foreach function needs to get an IEnumerable from the item it's trying to loop over. But why?

In my head there seems to be way more situations where you would want the behavior to be that it doesn't trigger at all.

I also understand that you can do;

foreach (var h in file.Headers ?? new())
{
    //do stuff
}

or;

listOfItems?.ForEach(item => // ... )
{
    //do stuff
}

So basically, why is the current behavior the preferred behavior? Is it like this in most other languages as well? Is it because of efficiency?

0 Answers
Related