Thursday, May 30, 2013

Properties with Validation

In general properties have a get {} and set {} accessor which is used to get and set the values of the underlying private member in the class, these properties just make sure that the values which is being set from the external source matches the expected data type of the underlying private member. Apart from this they do not perform any other validation.

There are specific where the value to be set to a private member should satisfy certain business validations, since the member is private there is no way to set the value directly from external sources, the only way to set a value to the member is through the set {} accessor, we can perform a set of validations in the set {} accessor before assigning values to the variable.

In the following example we impose a simple validation to the UserName property, the value assigned to the property should be a string of length greater than or equal to 8, else an exception should be thrown.
    class Employee
    {
        private string strUserName;
        //
        public string UserName
        {
            set
            {
                if (value.Length >= 8)
                {
                    strUserName = value;
                }
                else
                {
                    throw new Exception("Username should have atleast 8 characters.");
                }
            }
            get
            {
                return strUserName;
            }
        }
    }

If we try to assign an invalid value to the property as follows an exception will be thrown and the invalid values will be assigned to the property.
objEmployee.UserName = "Test";

Adding validations to the set {} assessors, makes sure that the integrity of the private members in the class are ensured, no external source can set invalid data.

Search Flipkart Products:
Flipkart.com

No comments: