I am writing a message processor. The processor receives messages through a stream of data. Messages may have different types, but all types have some common properties, for example length, check-sum, etc. Moreover, each type of message has its own properties as well.
For its implementation, I am thinking of making a class (say message class) that includes common properties, and inheritance from the message class to create individual classes for each message type. First, I am wondering if inheritance is a good solution in this case? or is there any other better way for it?
Also, I would like to pass a raw message to a method and that method returns me the corresponding properties to message (including common and individual). As individual properties change based on the message type, how can I implement the method to return me only one object? To better explain, I do not want it to return a different object for each message type. I would rather have a general object that has some specific properties based on another property like “MessageType”, something like below:
Message Class:
--- Length
--- Check-sum
--- MessageType
--- Property A
--- Property B
.
.
.
--- Property Z
Properties A to Z are individual properties and their number and type could be different based on “MessageType” Method.
Thanks in advance.
When you say “I do not want it to return a different object for each message type”, do you mean run time, or design time type? If you mean design time type, then that isn’t an issue, just have the method return the base object for all your messages.
If you do want to return just a single type at run time, then Eric J.’s answer has a good solution for that.
If you don’t like the idea of using a dictionary of sorts, and you’re using .NET 4.0. You can go the dynamic route. You’d still be using a dictionary, but the code accessing the message object wouldn’t look like a dictionary.
Calling code:
The call to
message.MessageTypewill simply access the property that is defined.The call to
Message.Lengthwill invoke the TryGetMember method since no property by that name is defined.