Cast to generic type in C#

Posted by Andrej on Stack Overflow See other posts from Stack Overflow or by Andrej
Published on 2009-06-16T18:02:04Z Indexed on 2010/03/28 8:23 UTC
Read the original article Hit count: 486

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about cast

Related posts about generic