Cast to generic type in C#
- by Andrej
I have a Dictionary to map a certain type to a certain generic object for that type. For example:
typeof(LoginMessage) maps to MessageProcessor<LoginMessage>
Now the problem is to retrieve this generic object at runtime from the Dictionary. Or to be more specific: To cast the retrieved object to the specific generic type.
I need it to work something like this:
Type key = message.GetType();
MessageProcessor<key> processor = messageProcessors[key] as MessageProcessor<key>;
Hope there is a easy solution to this.
Edit:
I do not want to use Ifs and switches. Due to performance issues I cannot use reflection of some sort either.