0

Using c# auto-implemented properties can I have a class that does the following (psuedo C# code because I get an error - which is below when trying to compile this):

public class Foo {
    public String HouseName { get; private set; }
    public int HouseId { get; private set; }
    public int BedsTotal { 
        get { return (BedsTotal < 0) ? 0 : BedsTotal; }
        private set;
    }
}

Error 5 'House.BedsTotal.set' must declare a body because it is not marked abstract, extern, or partial c:\src\House.cs

To me it seems like I should be able to get a body for the getter and rely on the private set being auto-generated like it would be if I did a { get; private set; } but that's not working.

Do I need to go the whole way and set up member variables, take the private setter off, and use the members vars instead?

Thanks!

Josh R
  • 1,970
  • 3
  • 27
  • 45

2 Answers2

3

Yes, you'll need to set up private variables because at the moment you will end up in a loop trying to read the get {} portion because it references itself.

Set up a private backing variable like this:

private int _bedsTotal;
public int BedsTotal { 
        get { return (_bedsTotal < 0) ? 0 : _bedsTotal; }
        private set { _bedsTotal = value; }
    }

Then you can access beds through the private setter

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
2

i whould go for an even more easier approach

private int _bedsTotal;
public int BedsTotal
{ 
    get
    {
        return (this._bedsTotal < 0) ? 0 : this._bedsTotal;
    }
    private set
    {
        this._bedsTotal = value;
    }
}

and so you can set the value of BedsTotal like this : this.BedsTotal = [integer];, no need to used other private methods since you can make use of the set

alexo
  • 936
  • 8
  • 16
  • This will allow other classes to set the value of `_bedsTotal`. OP wants to make the setter private – CodingIntrigue Sep 25 '13 at 07:09
  • 1
    yeah my bad, forgot the `private` term – alexo Sep 25 '13 at 07:20
  • Other classes see neither the setter nor the _bedsTotal member since they are both declared private. They are only allowed to use the getter EDIT: I already saw the updated version ;) – HaMster Sep 25 '13 at 07:21