Calling generic method with a T parameter determined at runtime

A

Anders Borum

Hello!

I'm trying to call a generic method by providing the T parameter at runtime,
as opposed to compile time (i.e. by specifying the T parameter in the method
call). I was under the impression that the CLR was able to infer the T type
dynamically - perhaps I was wrong or simply "asking the wrong question"? :)

public void CallingMethod()
{
User sender = new User();

// does not compile
this.GenericMethod<sender.GetType()>(sender);

// compiles just fine
this.GenericMethod<User>(sender);
}

public void GenericMethod<T>(object sender)
{
..
}

Thanks in advance.
 
B

Ben Voigt

Marc Gravell said:

Not sure what that buys you, unless you are emitting IL dynamically, because
if you call through reflection, you won't have any sort of type safety.
You'd be better off using a base class or interface instead of generics (or
use the base class as the generic type argument).

For this prototype, I can't see any value in having a generic:
public void GenericMethod<T>(object sender)
{
..
}

The only purpose of a generic is to have the return type or argument type
vary, within the function it is still treated according to the constraints,
not the actual type.

In other words, instead of using MakeGenericMethod and reflection, just call
GenericMethod<object>()

and cast any results as needed.
 
J

Jon Skeet [C# MVP]

Ben Voigt said:
Not sure what that buys you, unless you are emitting IL dynamically, because
if you call through reflection, you won't have any sort of type safety.
You'd be better off using a base class or interface instead of generics (or
use the base class as the generic type argument).

For this prototype, I can't see any value in having a generic:
public void GenericMethod<T>(object sender)
{
..
}

The only purpose of a generic is to have the return type or argument type
vary, within the function it is still treated according to the constraints,
not the actual type.

There are other possible uses - there's nothing to say that the results
can't depend on T, even if nothing passed or returned uses T directly.
It's effectively like passing a parameter of type Type in that case,
except that you can add constraints etc.

I agree it would be a pretty rare case, but it's not impossible.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top