Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection Get Variables in Method

Tags:

c#

reflection

How can i get varibles used in Method which then I will write their values on Console ?

like image 672
Ufuk özkanlı Avatar asked Aug 04 '12 08:08

Ufuk özkanlı


2 Answers

You cannot. Reflection does not extend to reading the values of method variables. It only handles the declaration metadata of variables. And even then, the compiler may have removed the variable you thought you declared. Reflection allows full access to fields (instance / static type variables), but not method variables.

There are tricks you can use like lambda expressions, but this changes their form (from method variables into instance fields).

like image 157
Marc Gravell Avatar answered Nov 06 '22 13:11

Marc Gravell


I don think its possible, but if you dig IL code and look at the Method.Body. You can know about the temporary, local variables used.

But it will be difficult to differentiate temps from variables cos all the syntactic sugar is gone

UPDATE: Jus while searching on this question found it. Not sure if it works.

System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
 System.Reflection.MethodBase methodBase = stackFrame.GetMethod();

 methodBase.GetParameters(); //Array of System.Reflection.ParameterInfo[]
 methodBase.GetMethodBody().LocalVariables; //List of Local variables declared in the body
like image 23
Vinoth Avatar answered Nov 06 '22 12:11

Vinoth