3

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.

3
  • Your last code statement is actually foreach(Type message in messageTypes). Anyway, for this what you want to do, I would not chose a generic method but rather a regular method having (Type messageType) as input argument. Commented Jan 18, 2013 at 8:50
  • This method's signature should probably be more like Broker.GetMessages(Type messageType);. I bet you are calling typeof(TType) inside that method, which indicates it shouldn't be generic at all. Commented Jan 18, 2013 at 8:51
  • You didn't read the post at all. I can't change the signature of the broker because it's a third party assembly ... Commented Jan 18, 2013 at 8:54

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I though calling the makeGenericMethod was expensive because it is using reflection. If it's not that's the way I will make it working
@Raffaeu: I don't know how expensive it is, but you should get code which works first, and then check the cost. You could cache the result of MakeGenericMethod by type if you really wanted to, but I wouldn't add that complexity until I'd got data to show that it was required.
Thanks for the suggestion, I will try to get my test fitness working and then see how expensive it is

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.