Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does return type of ICollection<Person> mean?

Tags:

c#

.net

interface

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.

like image 660
DenaliHardtail Avatar asked Dec 16 '22 21:12

DenaliHardtail


1 Answers

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.

like image 128
Reed Copsey Avatar answered Dec 31 '22 04:12

Reed Copsey