Search code examples
c#propertiesfieldautomatic-properties

c# properties, have a get with an auto-implemmented private set


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!


Solution

  • 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