1

I am completely new to events in c# and this is what I want to do:

I have two methods:

OpenPage1();    
OpenPage2();

When either of these methods is called, I want a third method named as PerformSomeTask() to be called.

I believe that this can be done by event handling. Could anyone tell me how to do this?

MD XF
  • 7,860
  • 7
  • 40
  • 71
Rameshwar
  • 541
  • 6
  • 22
  • Why not simply put a call to `PerformSomeTask()` in both `OpenPage`methods ? That said, [here's a good answer](http://stackoverflow.com/questions/6201257/making-method-in-another-class-call-an-event-in-calling-class-when-its-done) on event subscription/notification – Laurent S. Mar 25 '15 at 09:38

2 Answers2

3

All you have to do in your class is to add an event with a correct eventHandler (Action in your example). The eventHandler should correspond the method that will subscribe to this event. Then you fire the event from the openPage Methods. You must check for null in case no one subscribed to this event.

public class Foo
{
    public event Action theEvent;

    public void OpenPage1()
    {
        if (theEvent != null)
            theEvent();
    }

    public void OpenPage2()
    {
        if (theEvent != null)
            theEvent();
    }
}

public class Bar
{
    public int Counter { get; set; }

    public void PerformSomeTask()
    {
        Counter++;
    }        
}

And here's a test that you can run to see it all together:

[TestMethod]
public void TestMethod1()
{
    var foo = new Foo();
    var bar = new Bar();
    foo.theEvent += bar.PerformSomeTask;

    foo.OpenPage1();
    foo.OpenPage2();

    Assert.AreEqual(2, bar.Counter);
}
Al.exe
  • 483
  • 3
  • 6
1

Events is a big part of C#.

To be simple, you need first a delegate that describe type of called method. In your example, PerformSomeTask is void and take no parameters. So declare in your class

public delegate void PerformSomeTask();

Then, you need to declare event, which is the member that will called to launch your function

public event PerformSomeTask OnPerformSomeTask;

On your both methods, OpenPage1 and OpenPage2, you need to check if someone subscribe to your event, if yes, call it.

if(OnPerformSomeTask != null)
   OnPerformSomeTask();

This will launch every method that subscribe to your event. Subscribers can be multiple.

To subscribe, just do it like this :

YourClass.OnPerformSomeTask += MyVoidMethod;
[...]
public void MyVoidMethod() { DoSomething(); [...] }

Your void method will be called everytime your run OpenPage1 and OpenPage2

If you need some parameters, juste change your delegate to proceed.

public delegate void PerformSomeTask(string myParam);

Then, your methods will have this parameter as standard function parameter (call your event with your value to pass it as parameter to every subscriber function).

cdie
  • 4,014
  • 4
  • 34
  • 57