Raffaeu
Raffaeu

Reputation: 7003

Array of Type calling a generic method

I have a generic method with the following signature:

Broker.GetMessages<TType>();

It can be used in the following way:

IList<IEmailMessage> emails = Broker.GetMessages<IEmailMessage>();

I need to execute this method for a series of types available within an array of this structure:

var messageTypes = new [] { typeof(IEmailMessage), typeof(IFaxMessage) }

My final result should be something like this:

foreach ( IMessage message in messageTypes)
{
   Broker.GetMessages<xxx>();
}

The problem is that I don't know how to covert the Type in order to pass it as a generic. I know I can use reflection to invoke the method but I was wondering if there is any better way to accomplish this. I can change the array structure but not the method signature.

Upvotes: 3

Views: 143

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503419

No, you would need to use reflection. You're half way there already given that you've got a Type[] - any time you use typeof, you're heading down the road to reflection. Generics are geared towards cases where you know the types at compile-time - and although you've hard-coded those types into your messageTypes array, you're still disconnecting the compile-time knowledge of the types from the invocation of the method.

It's fairly straightforward to do this:

var definition = typeof(Broker).GetMethod("GetMessages");
var generic = definition.MakeGenericMethod(type);
var result = generic.Invoke(null);

Upvotes: 5

Related Questions