简体   繁体   中英

How do I set a default value that is invalidated by property setter checking?

I have two fields with matching properties, each with data validation in the setter. I want the default values to be flagrantly incorrect. Thus, I am default initializing them to '\\0' and -1 .

private char _zoneLetter = '\0';
private short _zoneNumber = -1;

This is so that the only way these values can possibly exist is if they were never set, as I have an exception thrown in the setters.

public char ZoneLetter
{
    get { return _zoneLetter; }
    private set
    {
        if (!char.IsLetter(value)) throw new ArgumentException("No special characters are allowed.");
        _zoneLetter = value;
    }
}

public short ZoneNumber
{
    get { return _zoneNumber; }
    private set
    {
        if (!Enumerable.Range(1, 60).Contains(value)) throw new ArgumentException("Must be an integral value in the range [1,60].");
        this._zoneNumber = value;
    }
}

The trouble is that when I enter perfectly valid data, the exception is still thrown, telling me that the value '\\0' is incorrect, even when 'a' is entered into the constructor parameter.

public UtmEvent(double unixTime, double easting, double northing, short zoneNumber, char zoneLetter)
    : base(unixTime)
{
    this.Easting = easting;
    this.Northing = northing;
    this.ZoneNumber = zoneNumber;
    this.ZoneLetter = ZoneLetter;
}

When I change the default values to something valid such as 'a' and 30 , my test checking that no exceptions are thrown passes. Please tell me what I'm missing. I'm new to .Net and have no idea what is going on, haha.

You have a capitalization error,

this.ZoneLetter = ZoneLetter;

should be

this.ZoneLetter = zoneLetter;

My eyes missed the this.ZoneLetter = ZoneLetter; line in the constructor. I was trying to assign the property to itself, resulting in the getter grabbing the default value of '\\0' and feeding it back into the setter's validation condition. Let this be a lesson that indicates the importance of not choosing shitty parameter names. Note to self: should not be the exact same as property or field names, with only the capitalization differing.

Oh, the humiliation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM