In C#
, I have a method with the following signature :
List<T> Load<T>(Repository<T> repository)
Inside Load()
method, i'd like to dump full method name (for debugging purposes), including the generic type. eg : calling Load<SomeRepository>();
would write "Load<SomeRepository>"
What i have try so far : using MethodBase.GetCurrentMethod()
and GetGenericArguments()
to retrieve information.
List<T> Load<T>(Repository<T> repository)
{
Debug.WriteLine(GetMethodName(MethodBase.GetCurrentMethod()));
}
string GetMethodName(MethodBase method)
{
Type[] arguments = method.GetGenericArguments();
if (arguments.Length > 0)
return string.Format("{0}<{1}>",
method.Name, string.Join(", ", arguments.Select(x => x.Name)));
else
return method.Name;
}
Retrieving method name works, but for generic parameter it always return me "T"
. Method returns Load<T>
instead of Load<SomeRepository>
(which is useless)
I have tried to call GetGenericArguments()
outside GetMethodName()
and provide it as argument but it doesn't help.
I could provide typeof(T)
as a parameter of GetMethodName()
(it will works) but then it will be specific to number of generic types eg : with Load<T, U>
it would not work anymore, unless I provide the other argument.
It looks like you can use:
The
ToString()
can probably be left out in this context.It looks like
GetCurrentMethod
gives you the "definition". You will have to "make" the constructed generic method like this.This "solution" still has the problem that if the generic signature of
Load<T>(...)
is changed to e.g.Load<TRep, TOther>(...)
, and theMakeGenericMethod
call in the body ofLoad<,>
is not updated, things will compile fine but blow up at runtime.UPDATE:Found a simpler and better solution:
There is a short thread Stack trace for generic method - what was T at runtime? on MSDN where it is claimed that no easy solution exists. See also Getting generic arguments from a class in the stack here on SO.
The answer of Jeppe Stig Nielsen is correct in terms of your requirements. In fact, your solution returns T and his returns the runtime type name. If you ask for something different, then try to rewrite your question. The below is another solution for one generic item:
Here is the output that you asked for:
In case if you want to have a generic solution for retrieving name and parameters of generic methods, try to use expression trees as in the following code sample:
The output:
I found a heavy weight answer to your question that uses IL beside reflection. The idea is to obtain body of parent method, that invokes child method, that we want to dump. From reflection we are able to obtain array of IL bytes, which we can read and turn back into appropriate method invocations along with the runtime values of their generic parameters.
The below is a simplified result code based on your sample:
Notice:
The below is a simple completion of Luo's class along with satelite objects: