In C#, there are several ways to check if a collection is empty. Depending on the collection type, you can use the Length, Count, or IsEmpty property, or 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);
With C# 11, you can use pattern matching to let the compiler choose the best method to check if the collection is empty. You no longer need to remember the correct property name.
C#
var collection = ...;
var isEmpty = collection is []; // Works for any collection type
Note that this approach is not exactly equivalent to checking the Length property. If the collection is null, checking the property throws a NullReferenceException, while 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!