Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement events through interface in C#?

Tags:

c#

interface

I have a problem: imagine I have a plugin-based system.

I need some kind of interface with which I could catch events from every plugin, which implements for example IReporting interface.

(IReporting) object.OnSomeEvent += <.....>

But I can't find a way to do that.

like image 813
Lukas Šalkauskas Avatar asked Jan 21 '09 13:01

Lukas Šalkauskas


People also ask

Can we have event in interface?

An interface can declare an event. The following example shows how to implement interface events in a class. Basically the rules are the same as when you implement any interface method or property.

CAN interfaces have events C#?

An interface can be created to define a contract containing members that classes that implement it must provide. Interfaces can define events, sometimes leading to classes that implement several interfaces being required to declare an event name twice.

Can interface contain delegates?

Interface can be inherited and implemented by any class and a Delegate can be created for a method on any class, as long as the method suits the method signature of the delegate. An Interface or Delegate is being used by an object. Both have no knowledge of the class that implement.

What is event in C sharp?

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.


1 Answers

Instead of (IReporting)obj.XXX you should write ((IReporting)obj).XXX

public interface IFoo
{
    event EventHandler Boo;
}

class Foo : IFoo
{
    public event EventHandler Boo;
    public void RaiseBoo()
    {
        if (Boo != null)
            Boo(this, EventArgs.Empty);
    }
}

...

private void TestClass_Boo(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

    ...

   object o = new Foo();
   ((IFoo)o).Boo += TestClass_Boo;
   ((Foo)o).RaiseBoo();

Regarding plugin framework take a look at existing solutions with good architecture, for example MEF

like image 50
aku Avatar answered Sep 21 '22 12:09

aku