I know I shouldn\'t be exposing a List
in a property, but I wonder what the proper way to do it is? For example, doing this:
public static
You don't need to worry about the overhead of cloning: wrapping a collection with a ReadOnlyCollection does not clone it. It just creates a wrapper; if the underlying collection changes, the readonly version changes also.
If you worry about creating fresh wrappers over and over again, you can cache it in a separate instance variable.
I asked a similar question earlier:
Based on that I would recommend that you use the List<T>
internally, and return it as a Collection<T>
or IList<T>
. Or if it is only necessary to enumerate and not add or antyhing like that, IEnumerable<T>
.
On the matter of being able to cast what you return in to other things, I would just say don't bother. If people want to use your code in a way that it was not intended, they will be able to in some way or another. I previously asked a question about this as well, and I would say the only wise thing to do is to expose what you intend, and if people use it in a different way, well, that is their problem :p Some related questions: