Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event must be of delegate type?

Tags:

c#

Not very familiar with declaring and using events and received error,

Event must be of delegate type

Basically want to pass IMyInterface as a dependency to another class where that class can subscribe to receive MyClassEvent events and the event data is MyClass.

public interface IMyInterface
{
   event MyClass MyClassEvent;
}

public class Implementation: IMyInterface
{
     event MyClass MyClassEvent;
     public void OnSomethingHappened
     {
         MyClassEvent?.Invoke(); // pass MyClass to subscribers
     }
}

public class AnotherClass(IMyInterface ...)
{
    OnMyClassEvent(MyClass args)
    {
       // do something
    }
}
like image 467
O.O Avatar asked Nov 05 '15 15:11

O.O


People also ask

How do you declare an event based on the delegate?

Use "event" keyword with delegate type variable to declare an event. Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events. The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method.

Is an event handler a delegate?

The EventHandler delegate is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must use the generic EventHandler<TEventArgs> delegate class.

What is events and delegates in unity?

Events in Unity are a special kind of multicast delegate and, generally speaking, they work in the same way as regular delegates. However, while delegates can be called by other scripts, event delegates can only be triggered from within their own class.

Can we use events without delegates?

Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.


1 Answers

You need to declare the event correctly and define the event args:

public class MyClassEventArgs : EventArgs { }

public interface IMyInterface
{
    event EventHandler<MyClassEventArgs> MyClassEvent;
}

public class Implementation : IMyInterface
{
    public event EventHandler<MyClassEventArgs> MyClassEvent;

    public void OnSomethingHappened()
    {
        MyClassEvent?.Invoke(this, new MyClassEventArgs());
    }
}

And to subscribe to it:

var implementation = new Implementation();
implementation.MyClassEvent += MyClassEvent;

private void MyClassEvent(object sender, MyClassEventArgs e) { ... }
like image 112
Trevor Pilley Avatar answered Sep 21 '22 15:09

Trevor Pilley