How to trigger event when a variable's value is changed?

James Mundy picture James Mundy · Apr 30, 2011 · Viewed 199k times · Source

I'm currently creating an application in C# using Visual Studio. I want to create some code so that when a variable has a value of 1 then a certain piece of code is carried out. I know that I can use an if statement but the problem is that the value will be changed in an asynchronous process so technically the if statement could be ignored before the value has changed.

Is it possible to create an event handler so that when the variable value changes an event is triggered? If so, how can I do this?

It is completely possible that I could have misunderstood how an if statement works! Any help would be much appreciated.

Answer

Jonathan Wood picture Jonathan Wood · Apr 30, 2011

Seems to me like you want to create a property.

public int MyProperty
{
    get { return _myProperty; }
    set
    {
        _myProperty = value;
        if (_myProperty == 1)
        {
            // DO SOMETHING HERE
        }
    }
}

private int _myProperty;

This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.