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

后端 未结 12 1895
旧时难觅i
旧时难觅i 2020-12-07 14:28

I often come across code like the following:

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

Basically, the

12条回答
  •  余生分开走
    2020-12-07 15:14

    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();  
    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.

提交回复
热议问题