Maintain one to one mapping between objects

Posted by Rohan West on Stack Overflow See other posts from Stack Overflow or by Rohan West
Published on 2010-04-23T05:38:47Z Indexed on 2010/04/23 5:43 UTC
Read the original article Hit count: 418

Filed under:

Hi there, i have the following two classes that provide a one to one mapping between each other. How do i handle null values, when i run the second test i get a stackoverflow exception. How can i stop this recursive cycle? Thanks

[TestMethod]
public void SetY()
{
    var x = new X();
    var y = new Y();

    x.Y = y;

    Assert.AreSame(x.Y, y);
    Assert.AreSame(y.X, x);
}

[TestMethod]
public void SetYToNull()
{
    var x = new X();
    var y = new Y();

    x.Y = y;
    y.X = null;

    Assert.IsNull(x.Y);
    Assert.IsNull(y.X);
}

public class X
{
    private Y _y;

    public Y Y
    {
        get { return _y; }
        set
        {
            if(_y != value)
            {
                if(_y != null)
                {
                    _y.X = null;
                }

                _y = value;

                if(_y != null)
                {
                    _y.X = this;
                }
            }
        }
    }
}

public class Y
{
    private X _x;

    public X X
    {
        get { return _x; }
        set
        {
            if (_x != value)
            {
                if (_x != null)
                {
                    _x.Y = null;
                }

                _x = value;

                if (_x != null)
                {
                    _x.Y = this;
                }
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#