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.
Recommended Articles:
- What is the Difference between Record and Class in C#
- How to Create CRUD operation using Angular and ASP.NET Core Web API
- WPF | Windows| Console Application | How to Call REST API in C#
- How to Remove Duplicates from an Array in C# without using a built-in function
- ASP.NET Core | How to Call Stored Procedure in Web API without Entity Framework