0

I want to make a simple debug tool that prints a variable and can be used anywhere inside my project:

public static DebugUtils {
  public static Log(object obj) {
    Debug.Log(GetOriginalVariableName(obj) + "=" + obj);
  }
  private static GetOriginalVariableName(object) {
    ...
  }
}

so in a class I can do:

public class MyClass {
  public void Foo {
    string mySpecialString = "abc";
    DebugUtils.Log(mySpecialString);
  }
}

and this will print (what I want):

mySpecialString=abc

I can find similar answer here, but it has to be in a same class, otherwise it prints this (what I DON'T want):

obj=abc

It grabs the variabale name of DebugUtils.Log instead... Any idea or builtin c# function so I can achieve this?

P.S. I'm in Unity 5 which using C# 5

Backs
  • 24,430
  • 5
  • 58
  • 85
Richard Fu
  • 616
  • 10
  • 27
  • Don't spam tags – Backs Feb 15 '18 at 04:01
  • Solution from https://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression us working – Backs Feb 15 '18 at 04:03
  • Your code won't compile. Have a look at `Foo`. – kara Feb 15 '18 at 07:10
  • I don't think it's a duplicate, I already mentioned and linked that answer, which doesn't work in my case. That answer only work for a SINGLE class, but I want use it in another class so I can reuse it anywhere in project. – Richard Fu Feb 16 '18 at 01:31

1 Answers1

0

You can ask obj for it's type. And you can ask a type for it's fields.

public class MyClass
{
    public string MyProperty { get; set; }
    public string MyField;
}

public static void PrintFields(object o)
{
    foreach (var item in o.GetType().GetFields())
    {
        Console.WriteLine("Field '{0}': {1}", item.Name, item.GetValue(o));
    }
    foreach (var item in o.GetType().GetProperties())
    {
        Console.WriteLine("Property '{0}': {1}", item.Name, item.GetValue(o));
    }
}

static void Main()
{
    MyClass obj = new MyClass()
    {
        MyProperty = "propertyValue"
    };
    obj.MyField = "FieldValue";

    object o = obj; // Box in object-class

    PrintFields(o);
}
kara
  • 3,205
  • 4
  • 20
  • 34
  • That's a bit different to what I ask, I wanna print any variable inside a method, not ALL* properties/fields of a class... but thanks for the reply anyway. – Richard Fu Feb 16 '18 at 01:27
  • Within a method .. uh. There are `LocalVariableInfos` but you can't get values out of them. In other articles the debugging-interface is suggested: https://stackoverflow.com/questions/5135939/is-there-a-simple-way-to-obtain-all-the-local-variables-in-the-current-stack-fram – kara Feb 16 '18 at 07:27