Reputation: 11330
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
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
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
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
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
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
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
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
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
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