Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch object state

Tags:

c#

.net

c#-4.0

I was working with angular-js and came across interesting feature that can watch object for changes.

I wonder if there is something similar in c#. I thought to create some watcher that will accept object to be watched, and may be check the hash code of the object periodically to find out if object changed, then rise an event. But that seems a bit inefficient.

Any ideas?

Thanks

like image 575
jekcom Avatar asked Aug 03 '26 21:08

jekcom


1 Answers

That wouldn't work anyway, firstly because there is no requirement for a property change to affect the hash code, and secondly, even if it did affect the hash code, it would be possible for the new hash code to be equal to the old hash code.

What AngularJS does is keep track of the last-known values, and then re-load all of the values, comparing them to the prior ones. If they're no longer equal, there has been a change.

You could do the same in C# if you want to.

But a way that's more common in C# is for the object being watched to implement the INotifyPropertyChanged interface, and raise the PropertyChanged event on each property change. This gives the object the ability to notify any interested watchers that properties have changed, without requiring the watcher to do any polling.