0

Let's have this class:

ExampleClass
{
    public List<string> MyValue { get; set; }
}

The question is how to restrict outside classes to modify of that property, means add object to collection, make new().

abc
  • 19
  • 3

2 Answers2

0

you can have something like this

public ReadOnlyCollection<string> MyValue {get; private set;}
Asif
  • 329
  • 1
  • 7
0

You could expose it as IEnumerable<string> instead of as a list. This interface will not allow adds. You can still store it as a list internally, as a private field, so that the class itself can add or remove if needed.

For example:

class ExampleClass
{
    private List<string> _myValue = new List<string>();

    public IEnumerable<string> MyValue
    {
        get
        {
            foreach (var s in _myValue) yield return s;
        }
    }
}

If the caller would like to work with its own list, it can of course do this:

var list = exampleClass.MyValue.ToList();

At which point the caller owns it and it is clear that anything it chooses to add has nothing to do with the original list.

John Wu
  • 50,556
  • 8
  • 44
  • 80