Groups | Blog | Home
all groups > c# > september 2007 >

c# : itemize variable via reflection



Bob
9/28/2007 10:42:03 PM
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
Jon Skeet [C# MVP]
9/29/2007 12:00:00 AM
[quoted text, click to view]

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

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Ben Voigt [C++ MVP]
10/1/2007 10:59:02 AM

[quoted text, click to view]

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

[quoted text, click to view]

Jon Skeet [C# MVP]
10/1/2007 5:39:57 PM
[quoted text, click to view]

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.

[quoted text, click to view]

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

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button