Maybe a stupid question, but..
In my code I use the following construction at several places.
void MyFunction()
{
DoSomething(myClass.myProperty)
myClass.PropertyChanged += (s,e ) => {
if (e.PropertyName == "myProperty") {
DoSomething(myClass.myProperty);
}
}
}
So I want to do something initially, and also do the same when the property changes in the future.
Now the thing is, MyFunction() gets called several time during my program’s execution. Will the delegate I assign to PropertyChanged be added evertime it passes through this method? (consuming more memory every iteration and slowing down the program) Or is the compiler/runtime smart enough to understand I should be only added the first time..? And if so, how does this work?
Many of the other answers suggest that you should check whether the
PropertyChangedevent isnullto prevent adding several listeners. A problem with that solution is thatPropertyChangedcan be non-nullif other parts of the code listens to the same event but for another property, like this.A better solution, in my opinion, would be to maintain a boolean flag which is initially false, and only set to true when
MyFunctionis called. Then, check this flag whether you need to add the event handler.