Declare an Event within an Interface

D

Derrick

How does one declare an event within an interface, so that every class which
implements that interface must implement that event? I think I just need to
specifiy the actual event as I would a function, but what about the
delegate?

Up to now, all my interfaces have only dealt with properties and functions.

Here's basically what I want to do (for example):

public interface IFoo
{
//Properties:
bool HasItems{get;}
Item[] GetItems{get;}

//Functions:
void AddItem(Item i);

//Events: --How do I do this? Where do I define the delegate?
void OnItemAdded(Item i);

}

Thanks,

Derrick
 
A

Artur Zakrzewski

Try this.


namespace MyNamespace
{
public delegate void MyDelegate();

public interface IMyInterface
{
event MyDelegate MyEvent;
}

public class MyClass : IMyInterface
{
public event EII.MyDelegate MyEvent;
}
}

HTH.

Artur
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Derrick,

You declare the events in the same way as you normaly do for classes. Don't
forget that events are pare (or three) methods - add, remove and invoke (the
latter is not supported by C#) that's why interfaces can have events

so you declare your interface as follows

class ClickedEventArgs
{

}

delegate void ClickedEventHandler(object sender, ClickedEventArgs e);

interface IFoo
{
event ClickedEventHandler Clicked;
}

In the interface declaration you don't declare any delegate data members
(because you cannot declare data members in interface), you just say that
classes implementing that interface have to declate this event.

Then you can implement the interface and the event as one normally do
class Foo:IFoo
{
public event ClickedEventHandler Clicked;

protected virtual void OnClicked(ClickedEventArgs e)
{
if(Clicked != null)
Clicked(this, e);
}
}

Or you gen go more advanced and provide some logic in add and remove
accessors

class Bar:IFoo
{

public event ClickedEventHandler Clicked
{
add
{
//Add a handler
}
remove
{
//Remove the handler
}
}


protected virtual void OnClicked(ClickedEventArgs e)
{
//Raise the event
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top