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();
}
}
}