itemize variable via reflection

  • Thread starter Thread starter Bob
  • Start date Start date
B

Bob

Hi,
Does anyone know if it is possible to use reflection to determine the
names and value types of the variables currently in scope?

Thanks,
Bob
 
Bob said:
Does anyone know if it is possible to use reflection to determine the
names and value types of the variables currently in scope?

No - in particular, local variables and parameters won't *have* names
when debug information hasn't been built.
 
Jon Skeet said:
No - in particular, local variables and parameters won't *have* names
when debug information hasn't been built.

You can get the types of local variables for any method though. See the
example in the LocalVariableInfo class. To get the current method you can
use the StackTrace class (is there a more efficient way to get just the top
method?)
 
Ben Voigt said:
You can get the types of local variables for any method though. See the
example in the LocalVariableInfo class.

Ah, haven't looked at that. I wonder if it gives entries for local
variables which are introduced by the compiler but don't represent
actual local variables in the original source code. Must play some
time.
To get the current method you can
use the StackTrace class (is there a more efficient way to get just the top
method?)

using System;
using System.Reflection;

public class ConvertFile
{
public static void Main(string[] args)
{

MethodBase b = MethodBase.GetCurrentMethod();
Console.WriteLine (b.Name);

MethodBody body = b.GetMethodBody();

foreach (LocalVariableInfo info in body.LocalVariables)
{
Console.WriteLine (info.LocalType);
}
}
}

Intriguing...
 
Back
Top