dotnetnoob
dotnetnoob

Reputation: 11330

List<T> exposed as IEnumerable<T>

I understand the hierarchy between the two and know how to convert between them, but is there anything fundamentally wrong with declaring a list like this?

IEnumerable<int> _bookmarkedDeals = new List<int>();

I don't need to change the list at any point, its either created or recreated as a whole.

As an alternative, possibly this

IEnumerable<int> _bookmarkedDeals = Enumerable.Empty<int>();

Upvotes: 1

Views: 305

Answers (9)

Jony Adamit
Jony Adamit

Reputation: 3416

(Unlike all answers here..) Yes. There is something very wrong with this declaration. You won't be able to use any of List<T> features without casting all the time back to list.

It's a good practice to return this type from your method if no list operations will be performed later on. But while you're in the same method - you're just making your life harder and less performant (because of the casts).

Upvotes: 1

Amiram Korach
Amiram Korach

Reputation: 13286

There is no syntax problem but I don't see how it could be useful. If you don't insert any item in this row, this list is going to stay always empty unless you cast it back to List<int>, so why you want to declare it as IEnumerable<int>?

Upvotes: 0

Szymon Rozga
Szymon Rozga

Reputation: 18168

Well, in this case, _bookmarkedDeals will be empty so the declaration is somewhat useless. That being said, nothing wrong with treating a List as an IEnumerable.

Upvotes: 2

Matthias Meid
Matthias Meid

Reputation: 12513

No, there is nothing wrong with it.

If this is a local variable, I see no benefit over just using var to create a variable of type List<int>. If you are just enumerating, it does no harm at all though. If it is a field, perhaps event publicly exposed, it can be very sensible not to expose it as a List<int> or IList<int> to keep the free choice of concrete type.

Upvotes: 0

M Afifi
M Afifi

Reputation: 4795

Nothing wrong with that, that's good design. Have a read of Arrays Considered Somewhat Harmful. Fabulous read about selecting the right interface.

Upvotes: 0

dcrobbins
dcrobbins

Reputation: 525

There's nothing fundamentally wrong with it, but why would you want to slice off some of the functionality that List provides (that IEnumerable doesn't)?

Upvotes: 0

MiMo
MiMo

Reputation: 11953

Nothing wrong.

If you never change the list in any way you could possibly use an array - it is slightly lighter than a list.

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68400

There is nothing wrong with that declaration but unless you have any specific restriction, IList<int> is a more appropiated interface for a list.

Upvotes: 0

Freeman
Freeman

Reputation: 5801

There is absolutely no problem with your declaration, although some people do like to declare the variable type precisely without any abstractization.

Upvotes: 0

Related Questions