1

I am in the process of creating a system that can receive messages from a variety of different sources.

Using the interface approach, I am adding a custom event which will pass the message back to the calling application.

I've used Vistual Studio's "scaffolding" using Ctrl-. to provide the implementation for the concrete class, but its added the add and remove elements but I dont really know how to wire that bit up.

Interface class

public class MessageEventArgs : EventArgs
{
    public Message { get; set; }
}

public interface MessageBroker
{
    void Start();

    event EventHandler<MessageEventArgs> OnMessageReceived;
}

Implementation class

public class MessageSourceA : MessageBroker
{
    event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
    {
        add
        {
            // What goes here
        }

        remove
        {
            // What goes here
        }
    }

    void MessageBroker.Start()
    {
    }
}

Main Program

    static void Main(string[] args)
    {
        MessageBroker sourceA = new MessageSourceA ();
        sourceA.OnMessageReceived += sourceA_OnMessageReceived;
    }

    private static void sourceA_OnMessageReceived(object sender, MessageEventArgs e)
    {
        // Do stuff with message
    }

Thanks...

Chris Hammond
  • 2,064
  • 5
  • 27
  • 53
  • You don't usually need any of that and can just put a semicolon after "OnMessageReceived" (and remove the body) unless you're doing something special. Then you can just call it like any other method (check that it's not null first). – ProgrammingLlama Jun 05 '17 at 10:01
  • 1
    Does it have to be explicit implementation? – M.kazem Akhgary Jun 05 '17 at 10:02
  • 1
    Please see [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/add) for more details and example [How to: Implement Interface Events](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-implement-interface-events) – Renatas M. Jun 05 '17 at 10:03

1 Answers1

1

You could normally implement from interface.

public class MessageSourceA : IMessageBroker
{ 
    public void Start(); 
    public event EventHandler<MessageEventArgs> OnMessageReceived;
 }

I suggest you to rename MessageBroker to IMessageBroker as its a naming convention. Since "I" helps to differentiate between class and interface when looking at code.

If there is proper reason to implement interface explicitly you need private event handler.

private event EventHandler<MessageEventArgs> _onMessageReceived;

event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived 
{ 
    add 
    { 
        _onMessageRecieved += value;
    }
    remove 
    { 
        _onMessageRecieved -= value; 
    }
}
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118