Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to retrieve the variable name (not value) of a property using reflection?

I am trying to retrieve the variable name of a property, instead of the value. I am currently using reflection, but if anyone has other suggestions it would be much appreciated.

I have three classes involved

A:

class A 
{
    public B bObject;

    int Number { return bObject.number; } //returns 3
}

B:

class B 
{   
    public int number = 3; 
}

C:

class C 
{
    public void myMethod() 
    {
        A aObject = new A();

        var aNumber = aObject
            .GetType()
            .GetProperty("Number")
            .GetValue(aObject, null);

        //this is the value. aNumber = 3.
        var objName = nameof(aNumber); //returns aNumber
    }

I want objName to return the string "bObject.number," the variable that was called inside the property. Is this possible with my current setup, and if not, does anyone have recommendations?

I'd rather not have another method in B to return "nameof(bObject) + nameof(bObject.number)" then call both that method and the prop due to redundancy. Thanks for your time.

like image 964
Wen Avatar asked Nov 08 '22 02:11

Wen


1 Answers

What you're trying to do here is to retrieve the Number method's body and then remove the "return" and the ";" to get only the value you want.

There's a very good example here that shows how to get the body of a method as a string: Getting a specific method source code from .cs file (at runtime)

When that's done, you can just parse out the "return" and ";" to get what you want.

That's not extremely elegant, but it does what you want.

like image 158
Maxime Tremblay-Savard Avatar answered Nov 15 '22 01:11

Maxime Tremblay-Savard