Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I Have a model Lets say Customer and Products and this is one to many between Customer and Products ie one customer can have multiple products
Now what is difference between
C#
public class Customer
{
public int Id { get; set; }
public int Name{ get; set; }
public ICollection<Products> Product{ get ; set ;}

}

// and 
public class Customer
{
public int Id { get; set; }
public int Name{ get; set; }
public List<Products> Product{ get ; set ;}

}
//And Which is better for dataModeling
Posted
Updated 25-Nov-14 21:20pm
v3

ICollection<T> is an interface, List<T> is a class.
Which means that the first definition can take any class which implements the ICollection interface (which supports methods such as Add, Remove, and so forth: http://msdn.microsoft.com/en-us/library/92t2ye13(v=vs.110).aspx[^]) where List implements ICollection, but extends it.

The first definition can take any class instance that implements ICollection<T> - this includes List<T> and any class derived from them - the second can only accept List<T> and classes derived from that.

The first is just a little more flexible than the second: it can take a wider range of classes - unfortunately not including LINQ values, which always implement IEnumerable<T> but not ICollection<T> which is derived from IEnumerable<T>.
 
Share this answer
 
Comments
Vishal Pand3y 26-Nov-14 3:12am    
Thanks @OriginalGriff
OriginalGriff 26-Nov-14 3:52am    
You're welcome!
ICollection is an INTERFACE, where List is a CLASS that IMPLEMENTS that specific INTERFACE!
So the second option is bonded to the type 'List' where the first option can work with any type that implements the ICollection interface...
 
Share this answer
 
Comments
Vishal Pand3y 26-Nov-14 3:02am    
ok I found it List inherts from IList<t>, ICollection<t>, IList, ICollection, IReadOnlyList<t>, IReadOnlyCollection<t>, IEnumerable<t>, IEnumerable
Please note, your code wouldn't compile (you need to give a name to your ICollection or List property).
In the first case, e.g.
C#
public class Customer
{
public int Id { get; set; }
public int Name{ get; set; }
public ICollection<Product> ProdColl{ get ; set ;}

}


You may use any of the classes implementing the ICollection<T> interface to set (and then get) the ProdColl property, e.g.
C#
LinkedList<ProductList>  = new LinkedList<Porduct>();
// add products to ProductList
Customer Cust = new Cuustomer();
Cust.ProdColl = ProductList;


While, in the second case, you have to use exctly a List<Product>.
 
Share this answer
 
Comments
Vishal Pand3y 26-Nov-14 3:19am    
ohh that was a typo but thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900