There is a custom class Student

public Student { public string Name {get; set;} public Student(string name, Teacher teacher) { Name = name; teacher.AddStudent(this); } } 

There is a second user class that stores a generic collection of instances of the Student class.

 public Teacher { private List<Student> students = new List<Student>(); public List<Student> GetStudents() { return students; } public void AddStudent(Student student) { students.Add(student); } } 

How to make the class Teacher's GetStudents () method return a collection of instances of Student that will be read-only?

  • one
    if you don’t want the student to change the field values, make them a private set - Grundy
  • The fact of the matter is that it is necessary that the properties of the Student class remain changeable, except for the case when the object of the Teacher class returns the list of its students for reading only. By analogy in ordinary life: there is a list of students in the dean's office, each entry in this list can be edited. Each student is attached to one teacher. The teacher is asked to list his students. He simply "shows" it, but does not give the right to change. It would be possible to simply send information about students in the form of a string, but I would very much like to give objects to readonly. - raskopin 4:34

1 answer 1

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); } }