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>
views:
136answers:
4An 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.
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
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.
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.