How can i get varibles used in Method which then I will write their values on Console ?
-
4What have you tried? Have you look at [this SO question](http://stackoverflow.com/questions/11739096/determining-all-types-used-by-a-certain-type-in-c-sharp-using-reflection)? – O. R. Mapper Aug 04 '12 at 08:35
-
But it gives me their types I need their values – Ufuk özkanlı Aug 04 '12 at 08:38
-
5They only have values in the scope of the method. Trying to get "values" from outside the method is meaningless. – spender Aug 04 '12 at 08:39
-
Is there any event like "methodreturning" may be i can use it – Ufuk özkanlı Aug 04 '12 at 08:44
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).

- 6,880
- 3
- 29
- 47

- 1,026,079
- 266
- 2,566
- 2,900
-
-
@Ufuk sure, maybe look at http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression – Marc Gravell Aug 04 '12 at 08:45
-
Would it help if the variable happened to be within a using() construct? – crokusek Aug 30 '18 at 17:46
-
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

- 2,419
- 2
- 19
- 34
-
2`LocalVariables` only gets variable metadata (minus the name of the variable) not the data on the vars themselves (see, https://msdn.microsoft.com/en-us/library/system.reflection.localvariableinfo(v=vs.110).aspx) – seebiscuit Dec 27 '17 at 16:28