Prevent other classes from altering a list in a class

c#

Solution

You won't be able to use an autoproperty.

public class SomeClass()
{
    private List<string> someList;
    public IList<string> SomeList { 
        get { return someList.AsReadOnly(); }
    }
}

Problem

If I have a class that contains, for example, a List<string> and I want other classes to be able to see the list but not set it, I can declare ``` public class SomeClass() { public List<string> SomeList { get; } } ``` This will allow another class to access SomeList and not set it. However, although the calling class can't set the list, it can add or remove elements. How do I prevent that? I guess I could use a field and return a copy of the List instead of using a property, but that just doesn't feel right. (This should be very simple but I must be missing something....)

Original source

Related problems