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
?
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.
}
Try this
IList<object> items = null;
items?.ForEach(item =>
{
// ...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With