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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With