Is if(items != null) superfluous before foreach(T

2019-01-16 15:20发布

I often come across code like the following:

if ( items != null)
{
   foreach(T item in items)
   {
        //...
   }
}

Basically, the if condition ensures that foreach block will execute only if items is not null. I'm wondering if the if condition is really needed, or foreach will handle the case if items == null.

I mean, can I simply write

foreach(T item in items)
{
    //...
}

without worrying about whether items is null or not? Is the if condition superfluous? Or this depends on the type of items or maybe on T as well?

12条回答
【Aperson】
2楼-- · 2019-01-16 15:56

It is not superflous. At runtime items will be casted to an IEnumerable and its GetEnumerator method will be called. That will cause a dereferencing of items that will fail

查看更多
【Aperson】
3楼-- · 2019-01-16 15:58

The test is necessary, because if the collection is null, foreach will throw a NullReferenceException. It's actually quite simple to try it out.

List<string> items = null;
foreach(var item in items)
{
   Console.WriteLine(item);
}
查看更多
We Are One
4楼-- · 2019-01-16 15:59

the second will throw a NullReferenceException with the message Object reference not set to an instance of an object.

查看更多
相关推荐>>
5楼-- · 2019-01-16 16:04

In C# 6 you can write sth like this:

// some string from file or UI, i.e.:
// a) string s = "Hello, World!";
// b) string s = "";
// ...
var items = s?.Split(new char[] { ',', '!', ' ' }) ?? Enumerable.Empty<string>();  
foreach (var item in items)
{
    //..
}

It's basically Vlad Bezden's solution but using the ?? expression to always generate an array that is not null and therefore survives the foreach rather than having this check inside the foreach bracket.

查看更多
看我几分像从前
6楼-- · 2019-01-16 16:06

The real takeaway here should be a sequence should almost never be null in the first place. Simply make it an invariant in all of your programs that if you have a sequence, it is never null. It is always initialized to be the empty sequence or some other genuine sequence.

If a sequence is never null then obviously you don't need to check it.

查看更多
聊天终结者
7楼-- · 2019-01-16 16:07

You do need this. You'll get an exception when foreach accesses the container to set up the iteration otherwise.

Under the covers, foreach uses an interface implemented on the collection class to perform the iteration. The generic equivalent interface is here.

The foreach statement of the C# language (for each in Visual Basic) hides the complexity of the enumerators. Therefore, using foreach is recommended instead of directly manipulating the enumerator.

查看更多
登录 后发表回答