Phil
Phil

Reputation: 103

How do I create a generic type dynamically in order to pass to generic method?

I've combed through existing questions/answers on this matter, but none of them spelled out exactly what I was looking for in a way I understood. Here is my snippet:

Type t = **?**

_SecondRole.ProvisionRelationship<t>(_FirstRole);

I believe I'm suppose to use reflection here, though I don't fully understand how. How do I define "t" so this works?

Thank you for any assistance.

Upvotes: 0

Views: 85

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064004

If the _FirstRole is an instance of the unknown t, for example from:

object _FirstRole = Activator.CreateInstance(t);

then you can exploit dynamic here:

dynamic _FirstRole = Activator.CreateInstance(t); // or whatever
_SecondRole.ProvisionRelationship(_FirstRole);

The second line is now a dynamic statement, evaluated in part at runtime (but with some clever cache usage) - which means it can perform generic type inference from the actual type of the object dereferenced from _FirstRole.


If that is not the case, then the only way to invoke that is via GetMethod and MakeGenericMethod - which is ungainly and not hugely efficient. In that scenario I would strongly suggest refactoring _SecondRole.ProvisionRelationship to accept a Type parameter rather than just being generic; you can of course still provide a generic version to avoid impacting existing code:

void ProvisionRelationship(Type type, SomeType role) {...}
void ProvisionRelationship<T>(SomeType role) {
    ProvisionRelationship(typeof(T), role);
}

and invoke as:

_SecondRole.ProvisionRelationship(t, _FirstRole);

Upvotes: 1

Related Questions