Question

In php, you can get the method's defined variables as an array:

function test($a,$b){
  print_r(
       get_defined_vars()
  );
}

Is it possible in C#?

Was it helpful?

Solution

You can use reflection for this.

If you want to do this inline, then you first need to determine the method you are currently in.

var currentMethod = System.Reflection.MethodInfo.GetCurrentMethod();

Then you can retrieve the parameters of that method:

foreach(ParameterInfo parameter in currentMethod.GetParameters())
{
    var name = parameter.Name;
    //...
}

OTHER TIPS

Something like...

string a = "hello";
int b = 20;
DateTime c = DateTime.Now;

foreach (LocalVariableInfo variable in MethodInfo.GetCurrentMethod().GetMethodBody().LocalVariables)
{
    Console.WriteLine(variable);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top