Stop other classes from adding to lists with "private set;"

Currently, I have a class (classB) that has a list --v

class classB
{
    public List<int> alist { get; private set; }
...

And I can accessing this class from another class (classA)

ClassB foo = new ClassB();
        foo.alist.Add(5);

Question is, can I stop this from happening? (make it unchangeable from other classes) Thanks!

Jon Skeet
people
quotationmark

Well, there are various options here.

  • You could change the property type to one which only provides a read-only interface (e.g. IReadOnlyList<T> or IEnumerable<T>. That doesn't stop the caller from casting the returned reference back to List<T> though.

  • You could create a ReadOnlyCollection<T> to wrap your real list, and only expose that - that wrapper will prevent the caller from being able to access the real list at all (other than by reflection)

  • If your code doesn't need to modify the collection either, you could just keep the ReadOnlyCollection<T> wrapper, or use the immutable collections package

  • You could avoid exposing the list at all, perhaps implementing IEnumerable<T> within your class

It really depends on exactly what your requirements are.

people

See more on this question at Stackoverflow