Canox
Canox

Reputation: 559

Calling public event to trigger method in another class in C#

I wanted to ask if this is Event possible in C#. I have not much worked with Events till now.

Say I have a class A which subscribed to a FormClosing Event of a form:

public class A
{
   private void f_FormClosed(object sender, FormClosedEventArgs e)
   {
     //Now here a public Event should be called
   }
}

Now there I want a public Event to be called. Let's say now I have another class B which has a certain method.

public class B
{
  public void DoSomething()
  {
  }
}

Now what I want to do:

A Form gets closed so class A is getting notified. There, a public Event gets triggered (which is somewhere in a public class). I want to subscribe my method in class B to this Event so it gets called when that happens. Is this possible? And how is the syntax? I haven't found something useful till now.

Edit: I can't create an instance of class B directly from class A.

Upvotes: 0

Views: 6051

Answers (1)

Ashley John
Ashley John

Reputation: 2453

Its possible .

  1. Create a new event in A.
  2. Raise the event within the eventhandler f_FormClosed
  3. Subscribe to this event in B.
  4. Within the eventhandler in B call the method DoSomething

For the syntax part you could check MSDN

// A delegate type for hooking up change notifications.
  public delegate void ChangedEventHandler(object sender, EventArgs e);

 // A class that works just like ArrayList, but sends event
 // notifications whenever the list changes.
 public class ListWithChangedEvent: ArrayList 
 {
    // An event that clients can use to be notified whenever the
    // elements of the list change.
    public event ChangedEventHandler Changed;

    // Invoke the Changed event; called whenever list changes
    protected virtual void OnChanged(EventArgs e) 
    {
      if (Changed != null)
       //you raise the event here.
        Changed(this, e);
    }
 }

Now in your other class do something like this

  class EventListener 
   {
     private ListWithChangedEvent List;

      public EventListener(ListWithChangedEvent list) 
      {
        List = list;
        // Add "ListChanged" to the Changed event on "List".
        //This is how we subscribe to the event created in ListWithChangedEvent class
        List.Changed += new ChangedEventHandler(ListChanged);
      }

     // This will be called whenever the list changes.
     private void ListChanged(object sender, EventArgs e) 
     {
      Console.WriteLine("This is called when the event fires.");
     }
 }

Upvotes: 3

Related Questions