0

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.

Phil
  • 103
  • 1
  • 1
  • 5
  • I'd say it is duplicate of [How to use reflection to call generic Method](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method/232621#232621), but it looks like your question about "what type to pass to [MethodInfo.MakeGenericMethod](http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx)... Please clarify. – Alexei Levenkov Mar 04 '13 at 05:19
  • What is `_FirstRole` here? is that a `t` by any chance? There are sometimes some tricks here, but it depends on the **exact** scenario. – Marc Gravell Mar 04 '13 at 07:02

1 Answers1

1

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);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900