Reputation: 5426
I come across the codes below:
public class Basket
{
public Guid BasketId { get; set; }
public DateTime Date { get; set; }
public virtual ICollection<BasketItem> BasketItems { get; set; }
public Basket()
{
BasketItems = new List<BasketItem>();
}
}
The part I do not quite understand is that why would we put
public virtual ICollection<BasketItem> BasketItems { get; set; }
instead of
public virtual List<BasketItem> BasketItems { get; set; }
One reason I can think of is that when this class is inherited, we can override BasketItems with different types?
What are other reasons of doing so?
Upvotes: 0
Views: 112
Reputation: 1030
one more thing: ICollection
is usually used in DataEntity for many-many/one-many relationships as well. You can refer (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) is a list of object that needs to be iterated through and modified.
Upvotes: 1
Reputation: 81
Avoiding concrete types when possible is normally a good design practice. It actually buys you a lot of strong advantages which are well documented in the Dependency Inversion Principle of SOLID - SOLID Wikipedia. Long story short, not putting yourself into a corner is good design because it allows the user to extend the property as they see fit and it lowers maintenance because, as an author, you don't have to create a new class type for every implementation of ICollection.
Another big benefit here is unit testing. Avoiding concrete types makes it a lot easier to mock dependencies in unit tests. This leads to test being smaller and more precise. There's a good explanation here of the benefits for more info - How do interfaces making unit testing and mocking easier?
Upvotes: 3
Reputation: 27357
Because BasketItems
doesn't need to be a list. Notice that the setter is public. It can also be overridden, as you pointed out.
It's essentially saying, as long as BasketItems
is a collection of BasketItem
, that's all we need to know. We don't care how the collection is implemented.
Upvotes: 3