I have a base Message class, and around 100 different subtype classes of Message that represent each type of message that can be processed. What I am currently considering doing is using a giant switch statement to create the message object. For example:
switch (MsgType)
{
case MessageType.ChatMsg:
Msg = new MsgChat(Buf);
break;
case MessageType.ResultMsg:
Msg = new MsgResult(Buf);
break;
... // 98 more case statements
}
Msg.ProcessMsg(); // Use a polymorphic call to process the message.
Is there a better way to do this? If so, can you show an easy code example.
EDIT
So, I tried doing this:
public class Test
{
public Test()
{
IEnumerable<Type> myEnumerable = GetTypesWith<MyAttribute>(true);
}
IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit)
where TAttribute : System.Attribute
{
return from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where t.IsDefined(typeof(TAttribute), inherit)
select t;
}
}
This appears to work in that myEnumerable now contains all 100 of the message subtypes, plus the base Message type as well. However, while I don't mind using reflection at the beginning of the program to load the types, using it to access the proper object in real time might be too slow. So, I would like to try out using a delegate.
The example in the comment below from @Mark Hildreth:
"So, you'd have a dictionary of >. Then, your mappings would be mappings[MessageType.ChatMsg] = x => new MsgChat(x);"
There are a couple of ways to interpret this code. One idea is to remove all 100 subclasses and just use one massive class with 100 delegate methods. That is a distant 2nd choice. The other idea and my first choice is for the above code to somehow create a message subclass object. But, I don't quite understand how it would do this. Also, it would be nice to keep the above technique in my Test class of getting all the types or delegates without having to write all 100 of them. Can you or anyone else explain how this can be done?