Question

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!

Was it helpful?

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top