James Jeffery
James Jeffery

Reputation: 12579

Adding Event to a Method

I have a HTTP class that I've created, and I would to, if possible, attach a method each time either HTTP.post() or HTTP.get() is called. I'd like to be able to attach the event either before, or after.

I see this being done in a lot of Frameworks for the web, such as Wordpress and Symfony, but I'd like to do something similar on my WinForms app.

What design pattern am I looking for to achieve this so I can go and Google it.

Upvotes: 1

Views: 97

Answers (1)

Jordan
Jordan

Reputation: 9901

You can create events on your objects and invoke them from anywhere in your code. I do this quite often.

public event EventHandler Getting;
public event EventHandler Setting;

void get()
{
    if (Getting  != null)
        Getting.Invoke(this, EventArgs.Empty);
}

void post()
{
    if (Setting  != null)
        Setting.Invoke(this, EventArgs.Empty);
}

Then other classes can handle these events something like this:

myHttp.Getting += myHttp_Getting;

public void myHttp_Getting(object sender, EventArgs e)
{

}

Edits:

You could also invoke the event like this:

void post()
{
    if (Setting  != null)
        Setting(this, EventArgs.Empty);
}

You can only invoke an event from within its own class. This is not a problem because being able to do otherwise would cause really confusing code. Always check if it is null, because if there are no subscribers it will be null and will through a NullReferenceException when you invoke it.

Upvotes: 4

Related Questions