Given a dictionary that maps some ID to a type:
Dictionary<int, Type> processIdToTypeMapping
I’m trying to iterate through the dictionary and cast an object to the type specified in the dictionary. The object comes from an MSMQ.
Here’s how I’m iterating the dictionary:
foreach (KeyValuePair<int, Type> processIdToType in processIdToTypeMapping)
I’ve tried to use generics:
private void CreateObject<T>()
{
FooBase fooBase = message.Body as T;
}
But that requires knowing the type at compile time. I can’t call CreateObject() like this:
CreateObject<typeof(processIdToType.Value)>(); // That can't work.
I tried using ChangeType():
private void CreateObject(Type fooType)
{
FooBase fooBase = Convert.ChangeType(message.Body, fooType);
}
But I get a compile time error that it can’t convert.
And I tried as:
private void CreateObject(Type fooType)
{
FooBase fooBase = message.Body as typeof(fooType);
}
How can I cast message.Body to the type in the dictionary?
From the comments, you are only trying to do dynamic type checking, so fortunately, dynamic casting is not necessary.