I have a private HashSet<string>
which is the backing field of a read-only property which should return a read-only collection such that callers cannot modify the collection. So I tried to:
public class MyClass
{
private readonly HashSet<string> _referencedColumns;
public ICollection<string> ReferencedColumns {
get { return new ReadOnlyCollection<string>(_referencedColumns); }
}
This does not compile as ReadOnlyCollection
accepts a IList<T>
which is not implememted by HashSet<T>
. Is there another wrapper I can use to save me from copy the items? For my purpose it is enough to just return something implementing ICollection<T>
(instead of IList<T>
) which is implemented by the HashSet<T>
.
Consider exposing the property as the type IReadOnlyCollection<>
instead, which will provide a read-only view of the HashSet<>
. This is an efficient way of implementing this, since the property getter will not require a copy of the underlying collection.
This will not prevent someone from casting the property to a HashSet<>
and modifying it. If you are concerned with that, consider return _referencedColumns.ToList()
in the property getter, which will create a copy of your underlying set.