Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an event when something changes in a class

Tags:

c#

events

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.

like image 351
Nickon Avatar asked Apr 15 '13 14:04

Nickon


People also ask

How can you tell if a event is triggered?

Using Developer Tools. Go to the sources tab. Click on the Event Listener Breakpoints, on the right side. Then perform the activity that will trigger the event, i.e. click if the event that used is click, double click if it is dblclick event.


1 Answers

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

like image 154
Yair Nevet Avatar answered Oct 10 '22 01:10

Yair Nevet