itemize variable via reflection

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
 
J

Jon Skeet [C# MVP]

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.
 
B

Ben Voigt [C++ MVP]

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?)
 
J

Jon Skeet [C# MVP]

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...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top