eakgul
eakgul

Reputation: 3698

Call Event Explicitly

Is that possible somehow to trigger an event which belongs another class in C#, such:

class foo
{ 
   public delegate void myEvntHandler();
   public event myEvntHandler onTesting;

   .
   .
   .
}

    class Main
    {
       public static void Main()
       {
         foo obj = new foo();

         ...

         obj.onTesting.Invoke();
       }
    }

on this sample I mean: obj.onTesting.Invoke();

Upvotes: 1

Views: 1023

Answers (3)

Nick H
Nick H

Reputation: 154

Short answer: No.

Longer answer: under the hood there no such thing as an "event" unlike delegates which are real objects. event is just a convenience for two methods (to add and remove handlers) and a private hidden field of type myEvntHandler.

Logically it makes no sense to raise an event from outside the class: The whole point of an event is that it is raised by the class when the class detects some trigger.

If you just want it to raise an event in order to test another class that has added a handler then the correct way to go is to:

  1. move the event to an interface
  2. implement the interface in your real class
  3. create a test class that also implements the interface and add your "RaiseEvent" method to that.
  4. Inject the interface into your unit under test

Upvotes: 0

Servy
Servy

Reputation: 203812

No. The whole purpose of events is to wrap a delegate while explicitly prohibiting all access to it other than adding/removing an event handler. The event keyword is there specifically to prevent any class other than the class that declares the event from invoking it.

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

No you can't invoke it directly from another class. That's the point of events (Encapsulation).

You need a helper method

class foo
{ 
   public delegate void myEvntHandler();
   public event myEvntHandler onTesting;

    public void RaiseEvent()
    {
        if(onTesting !=null)
            onTesting ();
    }
}

Then call RaiseEvent method instead

class Main
{
   public static void Main()
   {
     foo obj = new foo();

     ...

     obj.RaiseEvent();
   }
}

If you need to invoke it the way you did, just remove the event keyword and use a delegate. Which doesn't prevent you form doing so.(I don't recommend it)

Upvotes: 3

Related Questions