Search code examples
c#propertyinfo

Get object reference from PropertyInfo


I have a little problem, below my code:

public class A
{
    public string ObjectA { get; set; }
}

public void Run()
{
    A a = new A();
    a.ObjectA = "Test number 1";

    BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
    PropertyInfo myPropertyInfo = a.GetType().GetProperty("ObjectA", flags);
    object myNewObject = myPropertyInfo.GetValue(a);// Here should be reference

    a.ObjectA = "Test number 2";//After this line value myNewObject continued "Test number 1"
}

So my value myNewObject must be in output "Test number 2". Is there any way? It is this at all possible?


Solution

  • Wrong!

    You're getting the string rather than the instance of A using reflection.

    Changing A.ObjectA doesn't change the string reference. Actually, you're setting a different string to the backing string class field by the ObjectA property...

    Auto-properties are syntactic sugar to avoid explicitly declaring class fields to properties which perform nothing when getting or setting their values:

    // For example:
    public string Text { get; set; }
    
    // is...
    private string _text;
    public string Text { get { return _text; } set { _text = value; } }
    

    Now turn your code into regular one (no reflection):

    A a = new A();
    a.ObjectA = "hello world";
    
    object myNewObject = a.ObjectA;
    
    // Do you think now that myNewObject should change...? :)
    a.ObjectA = "goodbye";
    

    Is there any way? It is this at all possible?

    No.

    Maybe you can simulate this behavior using a Func<T>...

    Func<object> myNewObjectGetter = () => myPropertyInfo.GetValue(a);
    

    Now, whenever you call myNewObjectGetter() you're going to get the most fresh value of the whole property. BTW, this still doesn't address the impossible!