7

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

E.g. I have a class that has 100 fields and one of them is being modified externally or internally. Now I want to catch this event. How to do this?

The most I wonder if there is a trick to do this quickly for really extended classes.

Nickon
  • 9,652
  • 12
  • 64
  • 119

1 Answers1

13

As a best practice, convert your public fields to manual properties and implement your class with the INotifyPropertyChanged interface in order to raise a change event.

EDIT: Because you mentioned 100 fields I would suggest you to refactor your code like in this great answer: Tools for refactoring C# public fields into properties

Here is an example of it:

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

Community
  • 1
  • 1
Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
  • 2
    Rafactor your code! Look how it easy: [Tools for refactoring C# public fields into properties](http://stackoverflow.com/questions/1028679/tools-for-refactoring-c-sharp-public-fields-into-properties) – Yair Nevet Apr 16 '13 at 00:30
  • 1
    Also check out all the answers to [this question](http://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist). – TylerOhlsen Apr 16 '13 at 02:49
  • @Yair: good point, refactoring makes the whole operation faster and easier:) – Nickon Apr 16 '13 at 08:04