tags:

views:

136

answers:

4

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>

+2  A: 

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
+2  A: 

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 Butt
`IList<T>` seems like the best choice as it allows for access\assignment by index. `ICollection<T>` does not support indexing. The only drawback is that `IList<T>` exposes `Add` and `Remove` methods that will throw a `NotSupportedException` if called.
Brian Triplett
A: 

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
+2  A: 

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
ReadOnlyCollection violates LSP and forces the input collection to implement `IList<T>` which is quite restrictive however.
Lee
@Lee: the input collection is an array.
SLaks
@SLaks - 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<T>` doesn't implement `IList<T>`.
Lee