Which is better when check a list is null : not null or use Any

  • A+
Category:Languages

Which is better when check list is null ?

var newList;  if(newList!= null)  or newList.Any() 

In the above code, sometimes I check not null and sometimes I use Any(), I don't know which one is best practice and why ?

Any advice?

Thanks in advance

 


These are not the same.

Any will throw an exception if used on a null reference.

.Any() is equivalent to .Count() != 0

You may have to check for both, and you have to do the null check before calling Any() on your IEnumerable.

One way is to check them for both in one strike with the null-safe navigation ?.as in Thierry V's answer.

But sometimes you want to throw a custom Exception if you have a null value that you are not supposed to have, and treat an empty list as a correct input, so it all depends on the context.

Just remember that these are different.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: