Search code examples
c#.netarrayslistmutability

returning IList<T> vs Array in C#?


I was recently asking someone why he preferred to return a strongly-typed array over an IList. I had always thought that programming against an interface was the most flexible and best way program when faced with a project having a long life. So it struck me as odd when he replied:

We typically prefer immutable types over mutable ones. Arrays are immutable. IList is not.

I'm not entirely sure I understand this statement. Can anyone help clarify this?

Thanks for any help you guys can provide.


Solution

  • I think he maybe thought since an array's length property is immutable, then somehow arrays are more immutable than IList or maybe he used the wrong word and interchanged concrete with immutable. Who knows but it's an odd answer.

    I think with returning a List there is something slightly implied that it's ok to modify it or that it may change while returning an array doesn't imply that as much.

    For example, If you had an object model on top of a repository and had a method like GetCars() that returned a List and a junior programmer saw cars.Add(Car c) ... Would you think he was completely insane for thinking cars.Add(new Car()) might actually add a car into the repository? Arrays are just inherently more explicit.

    I think List usage is more appropriate in properties, like Page.Controls.Add

    I prefer returning arrays more often than List for several reasons.

    • Habit. Collections in 1.0/1.1 SUCKED

    • I prefer that my methods return the simplest & most lightweight object they can. If I need to make an Array a List it is trivial.

    • They can be used in .net 1.1 and it reduces the surface are of refactoring if I ever needed to support older versions of the runtime I can reuse at least some of my code or apply an identical object model.