3

For example

class School
{
    public List<Student> Students {get; private set;}
}

Here School is not immutable because the getter Students is a mutable collection. How to make the class immutable?

user1899020
  • 13,167
  • 21
  • 79
  • 154

2 Answers2

5

You could just expose an immutable list instead:

class School
{
    private readonly List<Student> _students = new List<Student>();

    public ReadOnlyCollection<Student> Students
    {
        get { return _students.AsReadOnly(); }
    }
}

Of course doing this still has no impact on the Student objects, so to be completely immutable, the Student objects would need to be immutable to.

poke
  • 369,085
  • 72
  • 557
  • 602
  • 1
    Good point. Deep immutability faces similar issues to deep copying – Bradley Thomas May 11 '16 at 17:46
  • @BradThomas How to implement deep copying in c#? There is no copy constructor in C#. – user1899020 May 11 '16 at 17:48
  • You can serialize or apply copy all the way through the hierarchy, this can be relatively simple or complex, depending on your types. see http://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically – Bradley Thomas May 11 '16 at 17:57
4

Simply make your backing field a private field and make the getter of the public property return a read-only version of the list.

class School
{
    private List<Student> students;

    public ReadOnlyCollection<Student> Students
    {
        get
        {
            return this.students.AsReadOnly()
        }

        private set;
    }
}
James
  • 1,028
  • 9
  • 20
  • I'd personally prefer @poke's answer because the public property clearly reflects the readonly-ness of the collection. – C.Evenhuis May 11 '16 at 17:37