Hossein Dehghani
Hossein Dehghani

Reputation: 93

How to automatically update a variable member of a class?

I defined a class in C# that has a variable member (for example x1). How can I link x to a variable outside of class (for example x2) such that anytime that x2 changes the variable x1 automatically gets updated?

class Point
{
    int x1;
}

void Main()
{
    int x2;
    Point p = new Point();
    P.x1=x2;
}

Upvotes: 2

Views: 348

Answers (2)

Gonzalo.-
Gonzalo.-

Reputation: 12682

as Matias said, since int values are not reference types, you can't update both simultaneously

Another way to solve the problem is to wrap your value into a class and use a setter property

class Point
{
    Point(Wrapped wrapped) {
       _wrapped = wrapped;
    }
    private Wrapped _wrapped;
    private int _x1;
    public int x1 {
       get { return _x1; }
       set {
        _x1 = value;
        _wrapped.x2 = value;
       }
    }
}

class Wrapped {
     int x2;
}

Now your main method will look like

void Main()
{
    var wrapped = new Wrapped();
    Point p = new Point(wrapped);
    P.x1= 3;
    Assert.AreEquals(p.x1, wrapped.x2); // true - both are equals to 3
}

disadvantage is that now both objects are coupled.

Upvotes: 1

Matias Cicero
Matias Cicero

Reputation: 26331

The problem is that int is not a reference type, hence, it's always copied by value.

To trivially accomplish what you seek, simply wrap the value in a reference type:

public class X
{
    public int value;
}

public class Point
{
    public X x1;
}

void Main()
{
    X x2 = new X();
    Point p = new Point();
    p.x1 = x2;

    x2.value = 50;
    Console.WriteLine(p.x1.value); //Prints out 50
}

Upvotes: 2

Related Questions