2

I have a class with a internal array field. I want to expose this array as a property, such that it maintains as much funtionallity of the orginal array but does not violate encapsulation by exposing the array directly. What are the various methods and pros and cons? I'm thinking specifically about IList<T> or Colleciton<T>

Brian Triplett
  • 3,462
  • 6
  • 35
  • 61
  • 1
    related: http://stackoverflow.com/questions/400135/c-listt-or-ilistt – Nick Mar 15 '10 at 19:50
  • What methods do you require in your public interface? – strager Mar 15 '10 at 19:52
  • As the underlying type is an array who's length is fixed by the class, I mainly need access and assignment by index enumeration capability. I don't want users to be able to add/delete/resize the unerlying array. – Brian Triplett Mar 16 '10 at 14:40

4 Answers4

2

An IList is an ICollection:

public interface IList<T> : ICollection<T>, 
    IEnumerable<T>, IEnumerable

You could implement ICollection, and if you need more methods from IList in the future, you can just change it without causing harm to the clients.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
2

IList<T> is bettere as it is a descendant of the ICollection generic interface and is the base interface of all generic lists. Along with you also have advantage for having funcionality from following interfaces

IEnumerable<T> and IEnumerable

this is the signature:

public interface IList<T> : ICollection<T>, 
    IEnumerable<T>, IEnumerable

see following for details

IList<T> Interface

Asad
  • 21,468
  • 17
  • 69
  • 94
  • `IList` seems like the best choice as it allows for access\assignment by index. `ICollection` does not support indexing. The only drawback is that `IList` exposes `Add` and `Remove` methods that will throw a `NotSupportedException` if called. – Brian Triplett Mar 16 '10 at 14:54
2

The corrrect way to do this is to expose a ReadOnlyCollection that wraps the array.

If you expose the array as an interface, malicious code can cast it back to an array and modify the values behind your back.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • ReadOnlyCollection violates LSP and forces the input collection to implement `IList` which is quite restrictive however. – Lee Mar 15 '10 at 20:14
  • @Lee: the input collection is an array. – SLaks Mar 15 '10 at 20:24
  • 1
    It might be an array now, but if he wants to change it (to a linked list say) then he will have difficulty since he's exposing a ReadOnlyCollection but `LinkedList` doesn't implement `IList`. – Lee Mar 15 '10 at 20:34
0

Personally I'd expose it as IEnumerable<T> and let the client decide which is best since this will give you the most freedom to change the underlying storage. If you really want to use IList<T> or ICollection<T> I'd choose ICollection<T> for the same reason.

Lee
  • 142,018
  • 20
  • 234
  • 287