Possible Duplicate:
why use IList or List?
I have the following:
public class CityViewModel
{
public CityViewModel() {
Details = Enumerable.Range(1,10).Select(x => new City.Detail()).ToList();
}
public string Topic { get; set; }
public City City { get; set; }
public IList<City.Detail> Details { get; set; }
}
The suggestion as a way to create Details was given to me. What I am unsure about is why the following line is declared as an IList:
public IList<City.Detail> Details { get; set; }
Would it not be more correct to declare this as:
public List<City.Detail> Details { get; set; }
Can someone explain the difference to me.
Using an interface rather than the class is definitely the right way to go, both for information hiding and testability reasons. I would even go further, and suggest using
ICollection<T>instead ofIList<T>if you can: this would give you even more flexibility as far as choosing an alternative implementation goes, while letting your users perform mostly the same operations.Moreover, I would probably not use an automatic assignable property for it: I’d return a read-only version, and provided separate methods for manipulating the list on my own class.
Here is what I would do:
This hides implementation of the list from users, does not let them modify the list behind your back, and does not even tell them that you’re using a
List. If you would decide to use, say, aHashSetat some later date, you’d be able to swap it in without a fear of breaking something in the code that uses your class.