Jamie
Jamie

Reputation: 864

Is there any point calling Any() before a for each?

I've been looking at some code I've refactored which makes use of the null object pattern so will always return an empty list if null.

However some of the other code within the function makes use of an Any() check for doing a ForEach().

Is there any benefit to doing so?

e.g.

var items = new List<items>

items.AddRange(GetItems(1))

if (items.Any())
{
   items.ForEach(item => { // Do something with item });
}

I realise as long as there is no need for the null guard this is safe, but I wondered whether there are any best practices with LINQ and C# relating to this.

Cheers, Jamie

Upvotes: 0

Views: 200

Answers (2)

Carbine
Carbine

Reputation: 7903

Sorry I am unable to say any best practices for Linq/C#, but I will share my thoughts on the usage of Any before ForEach

However some of the other code within the function makes use of an Any() check for doing a ForEach().

Having this Any() before ForEach() will passively suppressing null reference exception and carrying on with our operation. This appears to be good but actually the code permits others to send null values.

I normally use Debug.Assert(!=null) for the places where its possible to inject null values. This way these kind of errors can be captured in unit tests and ensure those who calls this code will be notified and wont allow to break this code. Because if null is tolerated, we will not address the root cause - which is we need to initialize objects in proper places.

Upvotes: 1

DerApe
DerApe

Reputation: 3175

The only check you could do is check if items is null, as you already said. But if you handle that case you should keep in mind to consider the else condition as well and how your application should react in that scenario.

Other than that, there is no need to check if there are items in the list if you just want to iterate over them.

Upvotes: 1

Related Questions