Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use eventhandler from baseclass

Is it possible for me to use ChangeHappend in my derived class. If so how?
If not, what should I do instead?

class Base
{
    public delegate void ChangeHandler(object sender);
    public event ChangeHandler ChangeHappend;

    private int _foo;
    public int Foo
    {
        set
        {
            if (_foo == value) return;
            _foo = value;
            ChangeHappend(this);
        }
    }
}

class Derived : Base
{
    private int _bar;
    public int Bar
    {
        set
        {
            if (_bar == value) return;
            _bar = value;
            ChangeHappend(this); // This line gives an error. How can I use ChangeHappend here in Derived?
        }
    }
}
like image 893
Nifle Avatar asked Jan 23 '23 11:01

Nifle


1 Answers

Use standard pattern: On[EventName]

public class MyBaseClass {
    protected virtual void OnSomethingHappend( EventArgs e ) {
        EventHandler handler = this.SomethingHappend;
        if ( null != handler ) { handler( this, e ); }
    }
    public event EventhHandler SomethingHappend;
}

public MyDerivedClass : MyBaseClass {
    public void DoSomething() {
        this.OnSomethingHappend( EventArgs.Empty );
    }
}
like image 189
TcKs Avatar answered Jan 30 '23 00:01

TcKs