6

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?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Milen Grigorov
  • 332
  • 3
  • 13

4 Answers4

10

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.
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
6

Try this

IList<object> items = null;
items?.ForEach(item =>
{
  // ...
});
Ashu
  • 467
  • 1
  • 7
  • 19
2

I stole the following extension method from a Project:

public static IEnumerable<T> NotNull<T>(this IEnumerable<T> list)
{
    return list ?? Enumerable.Empty<T>();
}

Then use conveniently like this

foreach (var item in myList.NotNull())
{

}
Charles
  • 2,721
  • 1
  • 9
  • 15
1

you can create extention method like this :

public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
 {
       return source ?? Enumerable.Empty<T>().ToList();
 }

Then you can write:

 foreach (var item in testList.OrEmptyIfNull())
    {
    }