I have a class which has two HashSet<String> collections as private members. Other classes in my code would like to be able to iterate over those HashSets and read their contents. I don’t want to write a standard getter because another class could still do something like myClass.getHashSet().Clear(); Is there any other way to expose the elements of my HashSets to iteration without exposing the reference to the HashSet itself? I’d love to be able to do this in a way that is compatible with for-each loops.
I have a class which has two HashSet<String> collections as private members. Other classes
Share
Expose a
IEnumerable<T>property:Of course, the user of this code can cast that
IEnumerable<T>to aHashSet<T>and edit elements, so to be on the safe side (while hurting performance), you can do:or:
A more performant method of protection, but less convenient to the caller, is to return an
IEnumerator<T>: