Andrew Gray
Andrew Gray

Reputation: 3790

Properties that update each other

So, in some C# code, I have something similar to the two properties:

private string _foo;
private string _bar;

public Foo
{
   get;
   set {
      _foo = value;
      Bar = _foo.Substring(3, 5);
   }
}

public Bar
{
   get;
   set {
      _bar = value;
      Foo = "XXX" + _bar;
   }
}

Question: Are C# properties subject to circular references/updates, like this example would seem to cause?

Upvotes: 2

Views: 664

Answers (4)

Vanlalhriata
Vanlalhriata

Reputation: 579

To avoid the infinite loop, here's an alternative to Philip Hanson's answer: run the setter lines only when the value actually changes. Be nice; this is my first post/answer

private string _foo;
private string _bar;

public Foo
{
   get;
   set {
      if (_foo != value)
      {
         _foo = value;
         Bar = _foo.Substring(3, 5);
      }
   }
}

public Bar
{
   get;
   set {
      if (_bar != value)
      {
         _bar = value;
         Foo = "XXX" + _bar;
      }
   }
}

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

Properties in C# are simple methods (getter and setter). You call one method from other method and vice versa. Result is completely expected.

Would this surprise you?

public void set_Foo(string value)
{
   set_Bar(value.Substring(3, 5));
}

public void set_Bar(string value)
{
   set_Foo("XXX" + value);
}

Call set_Foo("XXX12345") and.. you'll see the name of this site

Upvotes: 1

Philip Hanson
Philip Hanson

Reputation: 1867

You can avoid the infinite loop by updating the hidden field directly, like this:

private string _foo;
private string _bar;

public string Foo
{
   get { return _foo; }
   set {
      _foo = value;
      _bar = _foo.Substring(3, 5);
   }
}

public string Bar
{
   get { return _bar; }
   set {
      _bar = value;
      _foo = "XXX" + _bar;
   }
}

This will bypass the other property's setter, which eliminates the loop.

But... this generally causes maintenance headaches later on. Personally, I'd try to find an alternative design.

Upvotes: 3

Oded
Oded

Reputation: 499012

Are C# properties subject to circular references/updates, like this example would seem to cause?

Yes. You have a nice, infinite loop here.

Upvotes: 2

Related Questions