Search code examples
c#classmodel-associationsrelationships

How to implement the class - Student relationship in c#?


I want to implement a system, which represents a ClassRoom- Student relationship. I want to impose the constraint that Each ClassRoom can have any number of students, but one student can be at only one ClassRoom.

I have created two classes - ClassRoom and Student. I have created a list in the Class ClassRoom.How do I ensure that no one can inser the same student in two classRooms.


Solution

  • I hope it is on your experience level:

    ClassRoom

    public class ClassRoom
    {
        private List<Student> students = new List<Student>();
    
        public bool Contains(Student student)
        {
            return this.students.Contains(student);
        }
    
        public void Add(Student student)
        {
            if (!Contains(student))
                this.students.Add(student);
            student.StudentClassRoom = this;
        }
    
        public void Remove(Student student)
        {
            // if this contains, remove it anyway...
            if(Contains(student))
                this.students.Remove(student);
    
            // but do not set ClassRoom of student if she/he does not sit in this.
            if (student.StudentClassRoom != this)
                return;
    
            student.StudentClassRoom = null;
        }
    }
    

    Student

    public class Student
    {
        private ClassRoom stdClsRoom;
        public ClassRoom StudentClassRoom
        {
            get { return this.stdClsRoom; }
            set
            {
                if (value == this.stdClsRoom) //from null to null; from same to same;
                    return;                   //do nothing
    
                if (this.stdClsRoom != null)  //if it set from something
                {
                    ClassRoom original = this.stdClsRoom;
                    this.stdClsRoom = null;  // set field to null to avoid stackoverflow
                    original.Remove(this);   // remove from original
                }
    
                this.stdClsRoom = value;    // set field
    
                if (value != null)          //if it set to something
                    value.Add(this);        // add to new
            }
        }
    }