Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid null checking before foreach IList

Tags:

c#

null-check

I have the following code:

IList<object> testList = null;

... 

if (testList != null) // <- how to get rid of this check?
{
   foreach (var item in testList)
   {
       //Do stuff.
   }
}

Is there a way to avoid the if before the foreach? I saw a few solutions but when using List, is there any solution when using IList?

like image 528
Milen Grigorov Avatar asked Dec 03 '22 17:12

Milen Grigorov


2 Answers

Well, you can try ?? operator:

testList ?? Enumerable.Empty<object>()

we get either testList itself or an empty IEnumerable<object>:

IList<object> testList = null;

...

// Or ?? new object[0] - whatever empty collection implementing IEnumerable<object>
foreach (var item in testList ?? Enumerable.Empty<object>())
{
    //Do stuff.
}
like image 131
Dmitry Bychenko Avatar answered Dec 21 '22 06:12

Dmitry Bychenko


Try this

IList<object> items = null;
items?.ForEach(item =>
{
  // ...
});
like image 29
Ashu Avatar answered Dec 21 '22 04:12

Ashu