#701 – Centralize Business Rules Logic in set Accessors

You can use a property’s set accessor to enforce business rules for that property, e.g. min/max values for the property.

If you have a constructor that accepts initial values for some properties of a class, or methods that accept values, you can avoid checking constraints on these parameters by delegating the enforcement of the rules to the set accessor.

For example:

    public class Dog
    {
        // Public properties
        public string Name { get; set; }

        private int age;
        public int Age
        {
            get { return age; }

            // Set accessor checks for valid Age values
            set
            {
                if (value != age)
                {
                    if ((value > 0) && (value < 30))
                        age = value;
                    else
                        throw new Exception("Age is out of range");
                }
            }
        }

        // Constructor
        public Dog(string name, int age)
        {
            Name = name;

            // Don't validate age value here, but let set accessor do it
            Age = age;
        }
    }

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

#253 – Implementing a Read-Only Automatic Property

When using the automatic property syntax,C# requires that you define both a get and a set accessor.  But with the default syntax, you end up with a read/write property.

        public int Age { get; set;  }

But what if we want a read-only property, from the client code’s perspective?  Since we’re required to define the set accessor, it looks like client code would always be able to write to the property.

The solution is that we can add a private access modifier to the set accessor.

        public int Age { get; private set; }

With the set accessor private, code external to the class can read the property’s value, but not write to it.  But code within the class can still write to the property.

#250 – Using a set Accessor to Convert or Validate Property Data

We can use a property’s set accessor to do some validation on the new property value.  We may want to force the data to be within a particular range, do some conversion on the data, or throw an exception if an invalid value is specified.

Here’s an example where we use the set accessor of the Dog.Age property to enforce the constraint that a dog’s age can’t be less than 0.1.

        private float age;
        public float Age
        {
            get
            {
                return age;
            }
            set
            {
                // Enforce minimum age of 0.1
                age = (value < 0.1f) ? 0.1f : value;
            }
        }

Here’s another example, where we throw an exception if the user tries to set Name to an empty string.

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (value == "")
                    throw new Exception("Name can't be empty!");
                else
                    name = value;
            }
        }

#245 – Defining a Set Accessor for a Property

A set accessor for a property is the code that executes when the client of an object tries to write the property’s value.

The set accessor is defined using the set keyword.  The new property value is accessible using the value keyword, which is treated as a local variable having the same type as the property.

It’s common to store the value of a property in an internal private variable, known as the backing field.

In the example below, the set accessor for a property stores the new property value in the internal backing field whenever the property is written.  Note that the private variable and the public property name differ only in their case (name vs. Name).

    // Backing field--where the property value is actually stored
    private string name;

    public string Name
    {
        // Set accessor allows the property to be written
        set
        {
            name = value;
        }
    }

#243 – Property Get and Set Accessors

You can define a property in a class as a way of encapsulating a private field.  When declaring a property in a class, you define the property’s type, its name, and code for the property’s accessors.  The accessors are the means by which a user of the class reads and writes the property’s value.

When defining the accessors, you can have one of the following combinations:

  • Just a get accessor   (property is read-only)
  • Just a set accessor  (property is write-only)
  • Both get/set accessors  (property is read/write)

The get accessor defines the code that executes when some code tries to read the property’s value.

The set accessor defines the code that executes when a property value is written to.