tags:

views:

98

answers:

3

I have following class

public class ButtonChange
{
   private int _buttonState;
   public void  SetButtonState(int state)
   {
            _buttonState = state;
   }
}

I want to fire an event whenever _buttonState value changes, finaly I want to define an event handler in ButtonChange

Will you guys help me please??

P.S : I dont want to use INotifyPropertyChanged

A: 

Help yourself with google "c# events msdn"

Events tutorial (C#) - MSDN if you are using plain c#. INotifyPropertyChanged is for WPF - you don't need it for POCO/simple type events

Gishu
INotifyPropertyChanged is not just for WPF, it is used to notify clients, typically binding clients, that a property value has changed (from MSDN) http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
Prashant
technically it can be used.. however it is a cornerstone of WPF Data Binding; personally i've not heard of this interface before WPF came onto the scene.
Gishu
+2  A: 

How about:

public class ButtonChange
{
   // Starting off with an empty handler avoids pesky null checks
   public event EventHandler StateChanged = delegate {};

   private int _buttonState;

   // Do you really want a setter method instead of a property?
   public void SetButtonState(int state)
   {
       if (_buttonState == state)
       {
           return;
       }
       _buttonState = state;
       StateChanged(this, EventArgs.Empty);
   }
}

If you wanted the StateChanged event handler to know the new state, you could derive your own class from EventArgs, e.g. ButtonStateEventArgs and then use an event type of EventHandler<ButtonStateEventArgs>.

Note that this implementation doesn't try to be thread-safe.

Jon Skeet
Nice way to avoid them pesky null checks. Did not think of doing that. Don't know why. Probably automatic robotic habits.
tzup
Thanks a lot Jon, for StateChanged event I havent assigned any empty handler but still it worked, is it necessary do that, could you explain me bit more about it??
Prashant
If you don't have the "= delegate{}" bit in there, then if no-one subscribes to the event but you try to raise it anyway, you'll get a NullReferenceException.
Jon Skeet
+1  A: 

Property based event raising:

public class ButtonChange
{
    private int _buttonState;
    public int ButtonState
    {
        get { return _buttonState; }
        set 
        {
            if (_buttonState == value)
                return;
            _buttonState = value; 

        }
    }

    public event EventHandler ButtonStateChanged;
    private void OnButtonStateChanged()
    {
        if (this.ButtonStateChanged != null)
            this.ButtonStateChanged(this, new EventArgs());
    }
}
Alex Pacurar