null exception Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Fri, 20 Oct 2023 06:41:58 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 null exception Archives - Tech Insights 32 32 230003556 How to Return an Empty Collection in C# https://reactconf.org/how-to-return-an-empty-collection-in-csharp/ https://reactconf.org/how-to-return-an-empty-collection-in-csharp/#respond Fri, 20 Oct 2023 06:41:58 +0000 https://labpys.com/?p=1974 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 …

The post How to Return an Empty Collection in C# appeared first on Tech Insights.

]]>
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:

The post How to Return an Empty Collection in C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-return-an-empty-collection-in-csharp/feed/ 0 1974