Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke an event automatically when a function is called?

I have this kind of code:

public class Foo
{
  public SomeHandler OnBar;

  public virtual void Bar()
  {
  }
}

Foo is a base class and therefor other classes might inherit from it.
I would like the OnBar event to always be fired when Bar() is called even if it's not called explicitly inside Bar.
How can it be done?

like image 492
the_drow Avatar asked Jul 11 '10 15:07

the_drow


2 Answers

A common pattern is to have a non-virtual method that will do what you want that calls a virtual method. Subclasses can override the inner method to change the functionality, but the public method can be non-virtual on always raise the event first.

public class Foo
{
    public SomeHandler OnBar;

    public void Bar()
    {
        if (OnBar != null)
        {
            OnBar(this, EventArgs.Empty);
        }
        BarImpl();
    }

    protected virtual void BarImpl()
    {
    }
}
like image 98
Quartermeister Avatar answered Sep 27 '22 21:09

Quartermeister


Short answer: you can't. Not with what Microsoft gives you out of the box.

That said, take a look at "aspect oriented programming" in .NET. Google that, you might get something useful.

Added: The standard way would be to raise the event in the Bar() method and then require all derived classes to call the base implementation. But you can't enforce it.

like image 26
Vilx- Avatar answered Sep 27 '22 20:09

Vilx-