Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print property name (not what you would think) [duplicate]

Tags:

c#

This is a cursory question I can't quite answer.

The main program

class Program{
    static void Main(string[] args){
        Console.WriteLine("Begin");
        var myClass = new MyClass();
        Util.Print(myClass.Id);
        Util.Print(myClass.Server);
        Util.Print(myClass.Ping);
        Console.WriteLine("End");
    }   
}

How do I implement the Util.Print method to get this output to the console:

Begin
Id
Server
Ping
End
like image 602
Rasmus Avatar asked Mar 30 '09 19:03

Rasmus


2 Answers

Assuming you don't want to use strings, the most common answer is via an Expression - essentially emulating the missing infoof; you would have to use something like:

    Console.WriteLine("Begin");
    var myClass = new MyClass();
    Util.Print(() => myClass.Id);
    Util.Print(() => myClass.Server);
    Util.Print(() => myClass.Ping);
    Console.WriteLine("End");

Assuming they are all properties/fields (edit added method-call support):

 public static class Util
{
    public static void Print<T>(Expression<Func<T>> expr)
    {
        WriteExpression(expr);
    }
    public static void Print(Expression<Action> expr) // for "void" methods
    {
        WriteExpression(expr);
    }
    private static void WriteExpression(Expression expr)
    {
        LambdaExpression lambda = (LambdaExpression)expr;
        switch (lambda.Body.NodeType)
        {
            case ExpressionType.MemberAccess:
                Console.WriteLine(((MemberExpression)lambda.Body)
                    .Member.Name);
                break;
            case ExpressionType.Call:
                Console.WriteLine(((MethodCallExpression)lambda.Body)
                    .Method.Name);
                break;
            default:
                throw new NotSupportedException();
        }
    }
}
like image 173
Marc Gravell Avatar answered Oct 05 '22 13:10

Marc Gravell


In addition to Marc's answer: here is an article which explains several ways to do what you want to do (one such method uses expressions).

like image 34
Andrew Hare Avatar answered Oct 05 '22 11:10

Andrew Hare