I have a Dictionary to map a certain type to a certain generic object for that type. For example:
typeof(LoginMessage) maps to MessageProcessor
You can't do that. You could try telling your problem from a more high level point of view (i.e. what exactly do you want to accomplish with the casted variable) for a different solution.
You could go with something like this:
public abstract class Message {
// ...
}
public class Message : Message {
}
public abstract class MessageProcessor {
public abstract void ProcessMessage(Message msg);
}
public class SayMessageProcessor : MessageProcessor {
public override void ProcessMessage(Message msg) {
ProcessMessage((Message)msg);
}
public void ProcessMessage(Message msg) {
// do the actual processing
}
}
// Dispatcher logic:
Dictionary messageProcessors = {
{ typeof(Say), new SayMessageProcessor() },
{ typeof(string), new StringMessageProcessor() }
}; // properly initialized
messageProcessors[msg.GetType().GetGenericArguments()[0]].ProcessMessage(msg);