This post will discuss how to check whether a HashSet<T> is empty or not in C#.

1. Using Enumerable.Any() Method

The Enumerable.Any() method from LINQ is often used to determine whether any element of a sequence satisfies the specified predicate. If no predicate is supplied, the Any() method simply checks whether the sequence contains any values or not. For example, the following code uses the Any() method to check whether a HashSet<T> is empty or not.

Download  Run Code

 
The above code will throw a NullReferenceException if the HashSet<T> is null. We can easily use the null-conditional operator to check against a null, as shown below:

Download  Run Code

2. Using Count Property

Alternatively, you can use the Count property to check whether a collection is empty or not. The Count property returns the total number of elements contained in a collection in constant time. The following example demonstrates its usage for a HashSet<T>:

Download  Run Code

 
If the HashSet<T> is not guaranteed to be null, the above code might throw an exception. To handle null references, consider adding the null-check before accessing the nullable fields.

Download  Run Code

 
Here’s an equivalent version using the Count() method. Note that this uses LINQ.

Download  Run Code

That’s all about checking whether a HashSet<T> is empty or not in C#.