One class has a field. Second class should be able to reference that field and to change it. Since you cannot get the address of a field in memory, I have to use reflections. But my approach only works on non-encapsulated fields. So basically:
This works:
public class Dummy
{
    public int field;
    public Dummy(int value)
    {
        this.field = value;
    }
}
class Program
{
    public static void Main()
    {
        Dummy d = new Dummy(20);
        //Shows 20
        Console.WriteLine(d.field.ToString());
        d.GetType().GetField("field", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SetValue(d, 40);
        //It should show 40 now
        Console.WriteLine(d.field.ToString());
    }
}
This doesn't (throws NullReferenceException):
public class Dummy
{
    public int field { get; set; }
    public Dummy(int value)
    {
        this.field = value;
    }
}
class Program
{
    public static void Main()
    {
        Dummy d = new Dummy(20);
        //Shows 20
        Console.WriteLine(d.field.ToString());
        d.GetType().GetField("field", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SetValue(d, 40);
        //It should show 40 now
        Console.WriteLine(d.field.ToString());
    }
}
Why? How do I fix it? Can I even access an encapsulated object like that? Thank you!
 
     
     
     
     
    