Firing an event when something changes in the class

Is it possible to trigger an event when something changes in a given class?

eg. I have a class with fields of 100 , and one of them is modified externally or internally. Now I want to catch this event. How to do it?

The most interesting is whether there is a trick to do this quickly for really advanced classes.

+7
source share
1 answer

As a best practice, manually convert your public fields to properties and implement your class using the INotifyPropertyChanged interface to raise the event change.

EDIT: Since you mentioned 100 fields, I suggest you reorganize your code, as in this wonderful answer: Tools for refactoring open C # fields in properties

Here is an example:

 private string _customerNameValue = String.Empty; public string CustomerName { get { return this._customerNameValue; } set { if (value != this._customerNameValue) { this._customerNameValue = value; NotifyPropertyChanged(); } } } private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } 

Check this out: INotifyPropertyChanged Interface

+13
source

All Articles