5

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
Rasmus
  • 2,783
  • 2
  • 33
  • 43

3 Answers3

14

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();
        }
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

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

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
-1
public string Id {
    get {
      return "Id;"
    }
}

Hehe erm, though I assume that's not what you mean :-( The answer will likely be something to do with reflection.

Take a look at http://msdn.microsoft.com/en-us/library/ms173183(VS.80).aspx

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Dave Archer
  • 3,022
  • 20
  • 23
  • -1 this doesn't really answer the OPs question. I think he's really looking for something that can accept any random property – bendewey Mar 30 '09 at 20:14
  • +1, this kind of answer highlights the ambiguity in the OP question and promotes editing for clarification through peer pressure. – GWLlosa Mar 30 '09 at 21:29
  • I was gonna rate this down, but I agree with the comment above me. OP should really clarify. I was kinda confused. – Mike Christiansen Mar 30 '09 at 22:24