Roy
Roy

Reputation: 945

Quick way to monitor property value changes of a given class?

Say, I wrote a class ClassA. It works well until one day I wish to monitor the property value changes and react to the changes. What's the quickest way to do so?

One approach I can think of: make ClassA inherit INotifyPropertyChanged, and modify property getter/setter to trigger PropertyChanged event, and do something when event fired.

But this might mean tedius code change if ClassA has 10s of properties to be monitored.

Is there any more elegent way of wrapping or modifying ClassA, so that I can hook up some reaction logic?

Fantasizing: can Attribute do it? Maybe totally nonsense, I write a attribute and I just need to add this attribute to the properties I wish to monitor. It's better than adding/modifying getters/setters.

Upvotes: 3

Views: 2059

Answers (1)

CodeMilian
CodeMilian

Reputation: 1290

Something you may want to look into is using AOP (Aspect Oriented Programming) In short what this allows you do is put a wrapper around your class methods and properties and react before and or after invoking.

In the wrapper class you will have something like this

Invoke(Args[] Args, Aspect Aspect)
{
  //Do something like monitor something here 
  Aspect.Invoke //execution of method or property
 //Do other stuff here... maybe more monitoring
}

The beauty about this is separation of concerns. In your ClassA your code can continue to focus on whatever it was focused on before without worrying about the monitoring code. The wrapper is what handles the monitoring.

Reference material:

More info on AOP http://en.wikipedia.org/wiki/Aspect-oriented_programming

C# library that you can use to implement AOP in your applications. Castle Project/Dynamic Proxy http://www.castleproject.org/projects/dynamicproxy

Upvotes: 1

Related Questions