Exonto
Exonto

Reputation: 71

C# Subscribing to Events Using Interfaces

I have recently started working with C# events and I am really liking the ease of use they offer (I come from a java background where we have to do all this event stuff manually).

However, there is one thing from my java background that I am missing: the inheritance side.

In java, if you want to subscribe to an event, you would inherit an interface such as IKeyListener. The interface would contain all of the method event signatures which you would then implement in the subscribing class. Whenever a key would be pressed, these implemented methods would be fired. Much the same as C#. However, unlike in java, I am unable to identify which classes subscribe to certain events because they don't actually inherit anything.

So if I wanted a list of objects which have key press event support I could do

List<IKeyListener> keyListeners = new ArrayList<IKeyListener>();

However, I don't see any good way to do this in C#. How would I be able to create list similar to the one above? Preferably without much "hackiness".

Thank you.

Upvotes: 0

Views: 2073

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 27019

In C# you can define the event in an interface like this:

public interface IDrawingObject  
{  
    event EventHandler ShapeChanged;  
} 

Then you can do what you want and store them like this:

var shapes = new List<IDrawingObject>();

A class can then implement the interface like this:

public class Shape : IDrawingObject  
{  
    public event EventHandler ShapeChanged;  
    void ChangeShape()  
    {  
        // Do something here before the event…  

        OnShapeChanged(new MyEventArgs(/*arguments*/));  

        // or do something here after the event.   
    }  
    protected virtual void OnShapeChanged(MyEventArgs e)  
    {  
        if(ShapeChanged != null)  
        {  
           ShapeChanged(this, e);  
        }  
    }  
} 

So in other words the event becomes part of the interface and if a class implements that interface, the class must provide an implementation for the event as well. That way you are safe to assume the implementing class has the event.

Finally every event will need to share some info about the event. That class can inherit the EventArgs class like below:

public class MyEventArgs : EventArgs   
{  
    // class members  
}  

Upvotes: 3

Related Questions