I am writing an application that receives different kinds of messages from an external device. The messages are of different types and they are received from the device in the form of a string.

For each message type, there exists a DTO object representing the parsed message, and a parser class which parses the string message into the DTO.

I would like to implement a MessageHandler class which receives messages, parses the messages by using the correct parser, and provides a means for the client to provide handlers for the different kinds of messages.

I have come up with the following design:

internal class MessageHandler
    public event EventHandler<MessageTypeAEventArgs>? MessageAReceived;
    public event EventHandler<MessageTypeBEventArgs>? MessageBReceived;

    public void HandleMessage(string message)
        MessageType type = GetMessageType(message);
        switch (type)
            case MessageType.A:
                MessageA messageA = _typeAMessageParser.Parse(message);
                MessageAReceived?.Invoke(this, messageA);
            case MessageType.B:
                MessageB messageB = _typeBMessageParser.Parse(message);
                MessageBReceived?.Invoke(this, messageB);

When a message is received, the client invokes HandleMessage to pass the string message to the MessageHandler. The client can provide handlers by subscribing to the different kinds of events.

I am not convinced that this is a good design. I am looking for suggestions or design patterns which could help me improve it.

  • 3
    Improve how? What do you think is problematic with the code? What are you trying to optimize for?
    – Rik D
    Nov 5, 2023 at 16:49
  • 1
    I don't know if this would be an improvement in your case, but if all the message event arg types had a common base type of MessageTypeEventArgs, only one single MessageReceived event would be required and consumers could switch on the message type. Note that the case statement and the case expressions can switch on pattern matching expressions like type patterns: switch (eventArgs) { case MessageTypeAEventArgs a: ... Nov 5, 2023 at 17:43
  • 1
    Take a look at github.com/jbogard/MediatR
    – keuleJ
    Nov 5, 2023 at 21:01
  • Since this is working code, I think this question belongs on Code Review. See this answer
    – John Wu
    Dec 17, 2023 at 11:10


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.