Cast to generic type in C#


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.


The answer of @DanielPlaisted before generally works, but the generic method must be public or one must use BindingFlags.NonPublic | BindingFlags.Instance! Couldn't post it as a comment for lack of reputation.

By : Peter

    public delegate void MessageProcessor
By : wazazhang

I struggled to solve a similar problem around data table classes instead of messages. The root issue mentioned above of casting a non-generic version of the class to a derived generic version was the same.

In order to allow injection into a portable class library which did not support database libraries, I introduced a set of interface classes, with the intent that I could pass a type and get a matching generic. It ended up needing to implement a generic method.

// Interface for injection
public interface IDatabase
    // Original, non-functional signature:
By : JesikaDG

This video can help you solving your question :)
By: admin