I'm looking at some code samples for Entity Framework 4 and the author created a method that returns ICollection<Person>. I know ICollection is an interface. I know Person is the type of object in the collection. I know I'm getting back a collection of Persons.
The question. Why ICollection? Why not List<>? Why is an interface being used like this? I've used interfaces as "blueprints" for classes, specifying the required members but I don't really understand the usage here.
It's often better to return interfaces instead of concrete classes in public API.
This allows the implementation to change later. For example, it may, in fact, be returning a List<T>
at the moment. However, later, an optimization could be made to return a different type of collection which may have better memory efficiency, allow streaming, or one of many other advantages. As long as that class still implements ICollection<T>
, the implementation is free to switch without causing a breaking API change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With