I'm writing a C# socket networking library. I'm defining a BaseMessage class that I will derive all my message types from (e.g. UpdateNameMessage, UpdateStatusMessage).
I'll then be able to send them by calling the server's SendMessage method, which will take a BaseMessage message.
However, I'd like each BaseMessage to also contain a defined MessageType attribute. My issue comes from how do I standardize the numbering of these message types using a "best practice" style sort of way? I've currently got an example using an enum, however, for someone using the library they cannot inherit from an enum to add their own message types.
I thought about using a class, and defining consts. But that's rather ugly and can't be the answer.
I thought about writing a static class which you register your message types with on startup.
MessageTypeDictionary.Add("Heartbeat");
But I didn't like the way messages would be created later by the user writing the MessageType as a string, that can't be the best way:
new BaseMessage("Alice", "Bob", "Heartbeat")
My current code:
The server would send a message like this:
public void SendMessage(BaseMessage message) { }
A BaseMessage looks currently like this:
public class BaseMessage
{
public string To { get; protected set; }
public string From { get; protected set; }
public MessageType MessageType { get; protected set; }
public BaseMessage(string to, string from, MessageType messageType)
{
To = to;
From = from;
MessageType = messageType;
}
}
And finally, the MessageType enum looks like this
public enum MessageType
{
CONNECT,
DISCONNECT,
UPDATENAME
}
You have many options to chose from. Here is a solution based on Inheritance.
// Abstract base class
public abstract class BaseMessage
{
public string To { get; protected set; }
public string From { get; protected set; }
public abstract string MessageType { get; }
public BaseMessage(string to, string from)
{
To = to;
From = from;
}
}
// Concrete class for every message type.
public class HearthbeatMessage : BaseMessage
{
public override string MessageType
{
get
{
return "Hearthbeat";
}
}
}