yonan2236 yonan2236 - 3 months ago 22
C# Question

Set property not called for List object

Could someone help me below?
It seems Set is not called. How can I get around this?

Note that _students is set as the selectedObject of a property grid. So adding is done in the UI.

public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}

public class Record
{
List<Student> _students = new List<Students>();

public List<Student> Students
{
get
{
return _students;
}
set
{
// track changes here...
MessageBox.Show("value set!"); // this doesn't get called

_students = value;
}
}
}

Answer

I think you're having an issue with what set does with a list. You'll never see the message on adding a student to Record.Students, only when you set the list.

void Main()
{
    Student s = new Student() {
      Name = "fred",
      Age = 10
      };
    List<Student> _s = new List<Student>();
    _s.Add(s);

    Record r = new Record();
    r.Students = _s;  //You'll get a message here
    r.Students.Add(s);  //No message here
}

// Define other methods and classes here
public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Record
{
    List<Student> _students = new List<Student>();

    public List<Student> Students 
    {
        get
        {
            return _students;
        }
        set
        {
            // track changes here...
            MessageBox.Show("value set!"); 
            _students = value;
        }
    }
}