Checking if a collection is empty in C#

 
 
  • Gérald Barré

In C#, there are different ways to check if a collection is empty. Depending on the type of collection, you can check the Length, Count or IsEmpty property. Or you can use the Enumerable.Any() extension method.

C#
// array: Length
int[] array = ...;
var isEmpty = array.Length == 0;

// List: Count
List<int> list = ...;
var isEmpty = list.Count == 0;

// ImmutableArray<T: IsEmpty
ImmutableArray<int> immutableArray = ...;
var isEmpty = immutableArray.IsEmpty;

// Span: IsEmpty
Span<int> span = ...;
var isEmpty = span.IsEmpty;

// Extension method
List<int> list = ...;
var isEmpty = !list.Any();
var isEmpty = list.All(item => false);

Using C# 11, you can use pattern matching to let the compiler use the best method to check if the collection is empty. You don't need to remember the right property name. You can use the is operator to check if the collection is empty.

C#
var collection = ...;
var isEmpty = collection is []; // Works for any collection type

Note that the previous code is equivalent is not exactly equivalent to checking the Length property. If the collection is null, checking the property throws a NullReferenceException while the pattern matching returns false.

C#
int[] array = null;
var isEmpty = array.Length == 0; // NullReferenceException
var isEmpty = array is [];       // false

If you want to check if a collection is null or empty, you can use the following code:

C#
var isNullOrEmpty = array is null or [];

Note that you can use the same logic to check if a string is empty:

C#
// Both are equivalent, but string.IsNullOrEmpty(value) may be more common 😉
string str = "";
isEmpty = str is "";
isEmpty = str is [];

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub