This is very similar to the question but specific to Lists.
How to trigger event when a variable's value is changed?
Every time my list is modified I want to run a method.
I assumed using a property and putting a method within 'set' would be the correct way to approach this. I started with something like this
public class Stuff
{
private List<Things> _myThings;
public List<Things> MyThings
{
get
{
return _myThings;
}
private set
{
_myThings= value;
runWhenListIsChanged();
}
}
}
However, when I use a command like 'RemoveAt' or 'RemoveRange'
public class StuffChanger
{
Stuff.MyThings.RemoveAt(5);
}
It goes straight into the 'get' property and the list is changed.
I wrongfully presumed it would use set (as its changing the list) but that's not the case. When debugging (using the 'step into' tool in Visual Studio) I noticed the List can be modified by using the 'get' accessor.
In this particular case, I don't want to have a method being called every time the list is read by something, as this could get performance heavy or cause a stack overflow. So that isn't an option.
I'd be very grateful if anyone has any tips or code suggestions! Thanks very much.