Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Type calling a generic method

Tags:

c#

generics

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.

like image 269
Raffaeu Avatar asked Jul 27 '26 03:07

Raffaeu


1 Answers

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);
like image 108
Jon Skeet Avatar answered Jul 29 '26 18:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!