Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print name of the variable in c#

i have a statement

int A = 10,B=6,C=5;

and i want to write a print function such that i pass the int variable to it and it prints me the variable name and the value.

eg if i call print(A) it must return "A: 10", and print (B) then it must return "B:6"

in short i want to know how can i access the name of the variable and print it to string in c#. DO i have to use reflection?

After reading the answers

Hi all, thanks for the suggestions provided. I shall try them out, however i wanted to know if it is at all possible in .NET 2.0? Nothing similar to

#define prt(x) std::cout << #x " = '" << x << "'" << std::endl;

macro which is there in C/C++?

like image 955
Anirudh Goel Avatar asked Apr 08 '09 12:04

Anirudh Goel


2 Answers

The only sensible way to do this would be to use the Expression API; but that changes the code yet further...

static void Main() {
    int A = 10, B = 6, C = 5;
    Print(() => A);
}
static void Print<T>(Expression<Func<T>> expression) {
    Console.WriteLine("{0}={1}",
        ((MemberExpression)expression.Body).Member.Name,
        expression.Compile()());
}

Note: if this is for debugging purposes, be sure to add [Conditional("DEBUG")] to the method, as using a variable in this way changes the nature of the code in subtle ways.

like image 193
Marc Gravell Avatar answered Sep 22 '22 16:09

Marc Gravell


You can use lambda expressions:

static void Main( string[] args ) {
    int A = 50, B = 30, C = 17;
    Print( () => A );
    Print( () => B );
    Print( () => C );
}

static void Print<T>( System.Linq.Expressions.Expression<Func<T>> input ) {
    System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)input;
    System.Linq.Expressions.MemberExpression member = (System.Linq.Expressions.MemberExpression)lambda.Body;

    var result = input.Compile()();
    Console.WriteLine( "{0}: {1}", member.Member.Name, result );
}
like image 35
TcKs Avatar answered Sep 20 '22 16:09

TcKs