#700 – Using a set Accessor To Enforce Casing

A set accessor allows client code to give a property a new value.  You typically use the set accessor to do any required validation or conversion of the input value.  This is the point where you impose any business rules related to the value of the property being set.

For example, you might enforce a requirement that a particular string-based property always be uppercase.  Instead of throwing an exception if some calling code tries to set a property that is not uppercase, you can just automatically convert all values to uppercase.

    public class Car
    {
        private string licPlate;
        public string LicPlate
        {
            get { return licPlate; }
            set
            {
                if (value != licPlate)
                {
                    if (value.Length != 7)
                        throw new Exception("Invalid license plate number");
                    else
                        licPlate = value.ToUpper();
                }
            }
        }

    }

 

            Car c = new Car();
            c.LicPlate = "vpn 123";

            Console.WriteLine(c.LicPlate);

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment