How to Return an Empty Collection in C#

In C#, when returning a collection or array, It is better to return empty collections or a collection instance with no items. Returning an empty collection eliminates the need to check for null before iterating over the items in the collection, resulting in a cleaner method calling code.

The System.Linq.Enumerable class has a useful generic method called Empty. This method returns an empty instance of IEnumerable<T> (where T is your type parameter).

Here is an example of a return Empty Collection in C#:

        [HttpGet("getemployee")]
        public async Task<IEnumerable<Employee>> GetEmployees()
        {
            var results = this._employeeRepo.GetEmployeeListAsync();
            if(results.AsyncState == null)
            {
                return Enumerable.Empty<Employee>();
            }
            return await results;
        }

Output

If the result set returns a Null value, then “IF” condition is executed otherwise it returns collection items.

Return an Empty Collection in C#

Recommended Articles:

Leave a Reply

Your email address will not be published. Required fields are marked *