Never Return Null Collections - Here's Why #shorts

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

You can also consider to use IEnumerable as return type and Enumerable.Empty(), to return single static object instead of returning new List object every time which helps to reduce load on GC

AJIexa
Автор

There may be a semantic difference between returning no list (null) and an empty list.

andythebritton
Автор

Can I return Enumerable<int>.Empty() instead of new List<int>; ?

omerbilalcan
Автор

Hi Milan, it is weird, why are posting same thing again and again

thegaribovv
Автор

I disagree. Returning a null <anything> states that you couldn't find whatever you were looking for while an empty collection implies you found something, but that something was empty.

"Get all items in cart #51".
> Null? Cart #51 might not exist, or something else errored.
> Empty collection? Cart #51 is empty.

Better would be to use some sort of a Union type (OneOf<NotFound, DatabaseErrorOccured, IReadOnlyList<Item>>), but it still gives _some_ context.

If you're not using Nullable Reference Types you're doing C# wrong anyways.

modernkennnern
Автор

I have an extension method that created an emptylist if the list is null. CreateListIfEmpty<T>(this List<T> list)

myhjrhfgnb
Автор

I personally returning a Enumerable.Empty<T>, but great point as always

Zheorgyan