#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);

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: