I want to call my generic method with a given type object.
void Foo(Type t)
{
MyGenericMethod<t>();
}
obviously doesn’t work.
How can I make it work?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your code sample won’t work, because the generic method expects a type identifier, not a an instance of the Type class. You’ll have to use reflection to do it:
Do keep in mind that this is very brittle, I’d rather suggest finding another pattern to call your method.
Another hacky solution (maybe someone can make it a bit cleaner) would be to use some expression magic:
Note passing the ‘object’ type identifier as a generic type argument in the lambda. Couldn’t figure out so quickly how to get around that. Either way, this is compile-time safe I think. It just feels wrong somehow :/