Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerable.Empty<T>() equivalent for IList? [duplicate]

In some case I've to return an empty list of items in a method. Most of the case, I'm returning an IEnumerable<T>, so the Enumerable.Empty<T>() does exactly the job.

But I've one case where I've to return absolutely an IList<T> instance(we could use an IEnumerable, but this would results in a code much less efficient).

I didn't found an equivalent for the IList. I can perfectly imagine doing my own Singleton provider for empty list, but I would like to know if there is something I did miss?

like image 397
J4N Avatar asked Oct 06 '16 08:10

J4N


People also ask

What is enumerable empty?

The elements of each array in the collection are added to the resulting IEnumerable<T> only if that array contains four or more elements. Empty is used to generate the seed value for Aggregate because if no array in the collection has four or more elements, only the empty sequence is returned.

How check if list is empty C#?

Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.

Can IEnumerable be null?

The returned IEnumerable<> might be empty, but it will never be null .

How do you clear a collection in C#?

To handle empty collections, use the DefaultIfEmpty() method in C#. If an array is empty, then using this method will show the default method instead of displaying an error.


1 Answers

As Array is implementing IList use

Array.Empty<T>()
like image 121
Rafal Avatar answered Sep 21 '22 11:09

Rafal