0

Lets take an example

public class Sample 
{ 
    public int Execute() 
    { 
        int i=0; 
        return i; 
    } 
}

From the above code,Dynamically I want to identify all the available variables in Execute() method(currently only one variable i.e, i).Is there any possibility to do this??

Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
sowmya
  • 11
  • 7
  • http://stackoverflow.com/questions/11807142/reflection-get-variables-in-method possible duplicate – Sebastian L Jan 16 '17 at 09:32
  • 1
    you can do something like `method.GetMethodBody().LocalVariables` but local variables don't have name when compiled, so you can just get info about type and index at which order is was declared. – M.kazem Akhgary Jan 16 '17 at 09:36
  • @M.kazemAkhgary, We tried using this but we need variable name and value.Is there any other way?? – sowmya Jan 16 '17 at 09:42
  • yes, the other way is to store the code in string, and compile code at runtime, ill give links in a sec – M.kazem Akhgary Jan 16 '17 at 09:43
  • 3
    Why do you need to get the variable names? This is starting to sound like an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Abion47 Jan 16 '17 at 09:45
  • When you are writing code in string you know the variable names you put in. the only thing left is to compile your code stored in string. [here is the link](https://www.codeproject.com/tips/715891/compiling-csharp-code-at-runtime) note that compiling code is very performance intensive operation so be careful when doing this. also @Abion47 is right. you need to first tell why you need variable names? then see if its worth adding this complexity to your project. – M.kazem Akhgary Jan 16 '17 at 09:45
  • @M.kazemAkhgary, I have some code in one of the node in an xml(PFB Code).I'm trying to run this code using csharpcodeprovider(as you mentioned) int i=0; I have another node which makes use of this variable.So while compiling this code I need to declare it as a global variable.How can I do this?This is my actual problem – sowmya Jan 16 '17 at 10:17

1 Answers1

0

Unfortunately, that is not possible in C#. Reflection only allows you to examine types via the Type object.