Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Printing a Variable Name and Value - .NET Framework

RSS
Modified on Sat, Aug 06, 2011, 10:52 AM by Administrator Categorized as ┬ĚNet Framework

Code

static void Main(string[] args)
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 2; j < 4; j++)
        {
            Debug.Print("----------");
            Debug.Print(DebugMsg(() => i));
            Debug.Print(DebugMsg(() => j));
        }
    }
}
public static string DebugMsg<T>(Expression<Func<T>> expr)
{
    var body = expr.Body as MemberExpression;
    var name = body.Member.Name;
    var value = ((FieldInfo)body.Member).GetValue(((ConstantExpression)body.Expression).Value);
    return name + " = " + value;
}

Output

----------
i = 0
j = 2
----------
i = 0
j = 3
----------
i = 1
j = 2
----------
i = 1
j = 3
----------
i = 2
j = 2
----------
i = 2
j = 3

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.