4

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

Vladel
  • 230
  • 1
  • 4
  • 16
Rai Vu
  • 1,595
  • 1
  • 20
  • 30
  • 8
    Best practice is not to leave a bug in your code. `Any()` will throw Null exception if `newList` is actually `null` – Renatas M. Oct 05 '18 at 08:15
  • 2
    You can't use `newList.Any()` if `nesList` is `null`. – SᴇM Oct 05 '18 at 08:15
  • Possible duplicate [Checking for empty or null List](https://stackoverflow.com/questions/24390005/checking-for-empty-or-null-liststring). – SᴇM Oct 05 '18 at 08:27
  • I don't understand why this kind of questions get upvotes and even answers with upvotes these days. – SᴇM Oct 05 '18 at 08:31

3 Answers3

11

These are not the same.

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

With lists, you can think of .Any() as .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.

(*) : as noticed in a comment, .Any() is not actually implemented as Count() == 0. For lists, it's functionally equivalent, but it's best practice to use Any() to test if an IEnumerable is empty or not, because Count() might need to go through all the elements.

Pac0
  • 21,465
  • 8
  • 65
  • 74
  • 1
    In general, for sequences that are not `List`s, `Count() != 0` differs from `Any()` as it scrolls the entire sequence to calculate the number of items (that could be infinite!) before comparing it with 0. `Any()`, instead, returns as soon as an item is found or when the sequence is empty. – Luca Cremonesi Oct 09 '18 at 19:53
  • @LucaCremonesi indeed. Thanks for the comment. For the sake of correctness, I tried to formulate this point in the answer. Feel free to edit if you want and see a better phrasing. – Pac0 Oct 09 '18 at 20:29
5

null and Any() have the different purpose.

Any is used to check your list if it contains any item.

Before calling Any, your list must be not null, it not, it throws Null exception.

Think about newList?.Any()

Antoine V
  • 6,998
  • 2
  • 11
  • 34
3

As other answers say != null and Any() are different

I would write an extension method to make you expect.

public static class ExtenstionArray
{
    public static bool CheckAny<T>(this IEnumerable<T> list) {
        return list != null && list.Any();
    }
}

then you can use easier to check.

if(newList.CheckAny())
D-Shih
  • 44,943
  • 6
  • 31
  • 51