mclaassen
mclaassen

Reputation: 5128

Store a reference to a property of an object in a variable

In C# is there any way accomplish something like the following:

class A
{
    public int X { get; set; }
}

class B
{
    public /* ? */ OtherX;
}

var a = new A();
var b = new B();
b.OtherX = //?a.X?;
b.OtherX = 1; //sets a.X to 1
int otherX = b.OtherX //gets value of a.X

without resorting to doing this:

class B
{
    public Func<int> GetOtherX;
    public Action<int> SetOtherX;
}

var a = new A();
var b = new B();
b.GetOtherX = () => a.X;
b.SetOtherX = (x) => a.X = x;

?

Upvotes: 1

Views: 882

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61349

No, you can't do this exactly the way you described, since there is no ref int type, but you can put a wrapper around it so you can have both variables point to the same object that holds your value.

public class Wrapper<T>
{
   public T Value {get; set;}
}

public class A
{
   public Wrapper<int> X {get; set;}

   public A()
   {
       X = new Wrapper<int>();
   }
}

public class B
{
   public Wrapper<int> OtherX {get; set;}
}

var a = new A();
var b = new B();
b.OtherX = a.X;
b.OtherX.Value = 1; //sets a.X to 1
int otherX = b.OtherX.Value //gets value of a.X

Upvotes: 1

Related Questions