Don't return List<T> from a public member!
A friend of mine had a question about IList<T> and List<T>. He had noticed that some developers are returning IList<T> from methods, for example:
public IList<Customer> GetCustomers() { //... return customers; }
So he wonder why they don't just return a List<T> if the customer is of type List<T>. I can't say that all developers return IList<T> of the same reason, but one reason could be that they use interfaces instead of classes to make it easy return another kind of type which implements the IList<T>, but still the application will work because they working against an interface. Another reason could be to return a List to minimized the members of the returned type. Dino Esposito wrote a interesting article about returning List<T>. You can read it here. Dino Esposito wrote the following in the article:
"The advice of not using List<T> in a public API is definitely an example of an idiomatic design rule"
He also wrote that Cwalina (Author of the Framework Guidelines book) mention two reasons to not using List<T> publicly.
"One is that List<T> is a rather bloated type with many members not relevant in many scenarios. The other reason is that the class is unsealed, but not specifically designed to be extended."
If you take a look at the List<T> interface you will se a lot of methods. When we implements our applications we should make sure that other developers are using our code in the right way. In that case return a type with a thin interface and only the members which is needed. If we only need to return a List of Customers and the user of the method should only be allowed to iterate through the list, we should return a interface with only one method, the GetEnumerator, this can be done by returning the IEnumerable<T> interface instead of IList<T> or List<T>.
public IEnumerable<Customer> GetCustomers() { //... return customers; }
If we need more methods than just GetEnumerator, for example Count, we can instead return the ICollection<T> interface. Only return IList<T> if you know that you are need to use most (preferably all) of the interface members. If no interface fit your needs, just create your own. You don't want to expose more members than you need to expose. Have in mind that Users are a terrible thing, so make sure they can not harm your system, be ready for every single move they can do, protect your self from them, be defensive.
"Those who are good at getting rid of trouble are those who take care of it before it arises; those who are good at overcoming opponents are those who win before there is form." - Sun Tzu - The Art of War