Let's say we want to implement a method which will save a 'person' object to a file. The function would most probably look like this:
void Save(Person p) { }
Fair enough. Let's say a time comes when there is a need to save multiple person objects, how should the method look like now? How about this?
void Save (Person[] persons) { foreach (Person p in persons) { // save each person.. Save (p); } }
I have seen most projects use this approach which usually ends up changing to:
void Save(List<Person> persons) { foreach (Person p in persons) { // save each person.. Save (p); } }
Why? Because the consumer of the Save method decided to store the person objects in a List. With methods such as ToList() and ToArray(), we don't really have to provide overloads of the Save method to cater to lists and arrays, the caller can just use ToList() on an array when calling the Save(List
Of course there is a better way. As far as the Save() method is concerned, it's doing something bad i.e. assuming the collection of persons to be of a particular type, 'List' in this case. It doesn't have to be this way. If we use something like 'IEnumerable
void Save (IEnumerable<Person> persons) { foreach (Person p in persons) { // save each person.. Save (p); } }
Treat your collections well and you won't have to change them.