Anonymous
Anonymous

Reputation: 501

C# Can I make a property that gets and sets another property?

I have run into several times which I want to make one property that gets and sets another property. Of course, I know I can do this:

class Foo {

  public int Bar {
    get; set;
  }

  public int Baz {
    get {
      return Bar;
    }
    set {
      Bar = value;
    }
  }

}

But I'm wondering if there's a quicker way to do this.

Upvotes: 0

Views: 153

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

No, there is no shortcut syntax for this - explicitly implementing get/set for at least one of the properties is fine.

Ability to change same value via multiple properties feels confusing. Make sure you really need to do that - i.e. if you are implementing interfaces as you've commented you may be able to make one of the interfaces read only. Alternatively consider explicit implementation of at least one of the interfaces to minimize visibility of two setters for same property.

If making property read-only works you can use C# 6 syntax for get-only properties that is a bit shorter:

  public int Bar => Baz;

Upvotes: 1

Related Questions