This machine is not done. So we will do it manually.
Easy way
I suggest in the Teacher.GetStudents method to give copies of copies of the Student class. In this case, they, of course, will be changeable, but if you make changes to them, the originals will not be affected.
public class Teacher { private readonly List<Student> students = new List<Student>(); public List<Student> GetStudents() { return students.ConvertAll(s => new Student(s.Name, this)); } public void AddStudent(Student student) { if (!students.Contains(student)) students.Add(student); } }
Even in this case, it is necessary to check the collection for duplicates in the AddStudent method.
The method is more complicated
You can make an ImmutableStudent class that would be immutable. To minimize class differences for the rest of the program, I propose to introduce the common IStudent interface:
public interface IStudent { string Name { get; } } public sealed class ImmutableStudent : IStudent { public string Name { get; } public ImmutableStudent(string name) { Name = name; } } public class Student : IStudent { public string Name { get; set; } public Student(string name, Teacher teacher) { Name = name; teacher.AddStudent(this); } }
And to give in class Teacher like this:
public class Teacher { private readonly List<Student> students = new List<Student>(); public List<IStudent> GetStudents() { return students.ConvertAll(s => (IStudent)new ImmutableStudent(s.Name)); } public void AddStudent(Student student) { students.Add(student); } }