Nimral
Nimral

Reputation: 697

C# initialize list so not null if no items added

I have a routine which initializes a list ...

var items = new List<TodoItem>();
//... load items from a REST service ...
return items;

A subsequent routine tries to enumerate the list ...

foreach (var i in items)
{
    // ...
}

If the portal doesn't return any items, the list is null and the attempt to enumerate it fails ... the reasons have already been discussed.

Till now I did a != null check before the enumeration. Now I read a SO post where someone suggest that it was "bad practice" to return null in case a list has no items.

How do I initialize the list as an empty list which can be enumerated, instead of letting it be null? the only way that came to my mind was a sequence like

var items = new List<TodoItem>();
items =  Enumerable.Empty<TodoItem>()

This won't compile:

Cannot implicitly convert type System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?).

Trying to use an explicit cast ...

items = (List<TodoItem>)Enumerable.Empty<TodoItem>();

fails with a runtime exception "invalid cast"

Can anybode advise how I can properly initialize my list?

Upvotes: 0

Views: 4103

Answers (1)

Jonathan Wood
Jonathan Wood

Reputation: 67195

var items = new List<TodoItem>();

Creates an empty list. Done.

If you're doing this and it ends up being null, then your code is setting it to null and you haven't shown that code. Maybe it has something to do with your "load items from a REST service" code?

Upvotes: 8

Related Questions