Friday, 4 March 2016

A public .NET property

Another way of doing encapsulation is using .NET properties. Properties in .NET are nothing but simplification of accessor and mutator methods.
Below shown is same Company class as was shown in previous post but with using property syntax :

class Company
{
    // field-data declared private
    private string nameOfCompany;
    private int licenseNumber;

    //property 'Name' to get and set the value
    public string Name
    {
      get
         { return nameOfCompany; }
      set
         {  // check condition before assigning value to private field-data
            if(value.Length < 26)
             nameOfCompany = value;
           else
               Console.WriteLine("Name exceeds maximum limit");
          }
     }
    //similarly property 'LicenseNum' for private field-data licenseNumber
    public int LicenseNum
    {
       get
         { return licenseNumber; }
      set
         { // check condition before assigning value to private field-data
            if(value != 0 && value < 0)
             licenseNumber = value; 
           else
               Console.WriteLine("Invalid License Number");
          }
    }


}

Note: 

This syntax of property is little compact than writing two separate methods i.e. accessor and mutator methods as shown in the previous post. In-short the syntax is:

public returnType PropertyName
{
get { return field-data; }
set { if( test value) field-data = value; else Console.WriteLine("Sorry");}
}
I highlighted the 'value' keyword in set {  } piece of code, in-order  to stress upon it's importance. When some code set some value by calling the property syntax, then that value is automatically captured by 'value' keyword of the property i.e. there's no need of explicit declaration of temporary variable to store the value and later assign it to field-data as we use to do in mutator method.

class Program
{
static void Main(string[] args)
{
Company objRef = new Company();

//here we're setting the property 'Name' to assign value to private field-data //'nameOfCompany'
objRef.Name = "XYZ InfoTech Pvt. Ltd";

//here we're setting the property 'LicenseNumber' to assign value to private field-data //'licenseNumber'
objRef.LicenseNum = 12343;

//here we're calling the property 'Name' which further will call the get scope of the property //and returns the value it's supposed to send back
Console.WriteLine("Company name is :  {0}" , objRef.Name);

Console.ReadLine();
}
}

This is how the property syntax used in the code.



No comments:

Post a Comment