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?
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?
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.
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;
}
}