Working with "Properties" in C#

by kiranpvn kumar on 2/7/2012 2:36:19 AM
Rated 0 from 0 votes
Brief: Demonstrates on defining/working with "Properties" in .NET
Posted to: Basics of Object Oriented Programming in .NET
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

While we can use "fields" (or class level variables) to store data, it is not a good idea to directly expose the data out of class (through object). We need to ensure that the data being stored in an object is always good and follows our business principles.

Sample Scenario:  Imagine that I would like to store subject marks in a field (through object) and the rule is that the subject marks should always be between 0 and 100.  If we directly expose the field outside the class, we cannot stop others assigning some stale data.  Before any one can assign value to our field, we need to ensure that it follows all of our rules (and clean if necessary).  This can be easily accomplished using "Properties" in .NET.

"Properties" are very similar to methods except that these can be assigned and accessed at the same time (like a variable).  "Properties" do not occupy any memory.  They validate the data (if coded accordingly) and work with internal members (usually "private" variables) to store/retrieve correct (or accurate/good) data. These act like the mediators between the data (to secure data) and the outside world.

"Properties" will have two sections: a "Getter" (get) and a "Setter" (set).

"Setter" gets executed when a value is assigned to the property.  "Getter" gets executed when any one tries to retrieve value from the property (ex: assigning property to a variable).  

If a "Property" contains only "Set", it is called as "WriteOnly" (cannot be used to retrieve value).  If a "Property" contains only "Get", it is "ReadOnly" property (cannot be assigned with any value).

Following sample demonstrates the following:
  • defining "private" members to hold data.  These are not accessible out side the class (including "Main")
  • defining and working "Properties" in .NET
  • Defining "WriteOnly" Properties
  • Assigning values to Properties
  • Retrieving values from Properties.

01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05.  
06.namespace Properties
07.{
08.    class BankAccount
09.    {
10. 
11.        // The "private" members are never exposed outside the class
12.        // These members hold data (but not the properties)
13.        private int cust_no;
14.        private string cust_name; // Used to work with 'CustomerName' property
15.        private int bal;          // Used to work with 'Balance' property
16.  
17.        public BankAccount()      // Default Constructor
18.        {
19.           //No body. Default constructor can be empty. Does nothing when an object is created (with no parameter)
20.        }
21.        public BankAccount(int cust_no, string cust_name, int bal) // Parameterized constructor
22.        {
23.            this.cust_no = cust_no;
24.            this.cust_name = cust_name;
25.            this.bal = bal;
26.        }
27.        public int GetBalance()
28.        {
29.            //Simple for now, with no major code
30.            return bal;
31.        }
32.        public string CustomerName //The property which works with 'cust_name' behind the scenes
33.        {
34.            set //Executes when a value is assigned to "CustomerName"
35.            {
36.                cust_name = value; // 'value' is a reserved word which holds the value when the property is assigned.  We can enforce our business validations here if we need (say customer name should have at least 10 characters etc.)
37.            }
38.            get //Executes when "CustomerName" is assigned to another variable (or when we try to access it)
39.            {
40.                return cust_name;
41.            }
42.        }
43.        public int Balance  //WriteOnly property - will allow only to assign and it will not return any value
44.        {
45.            set //As we have only "set" with no "get" it is called "WriteOnly" property
46.            {
47.                bal = value;
48.            }
49.          //If we have only "get" with no "set" it is called "ReadOnly" property.  "ReadOnly" properties can only be used to retrieve values and not to assign values.
50.        }
51.    }
52.    class Program
53.    {
54.        public static void Main(string[] args)
55.        {
56.            //Creating an Object and passing values through parameterized constructor
57.            BankAccount a = new BankAccount(101, "Jagadeesh", 100);
58.  
59.            //Retrieve balance using traditional method (which returns a value)
60.            Console.WriteLine("Balance is : {0}", a.GetBalance());
61.  
62.            //Using "CustomerName" property, we are going to assign/set the customer name
63.            a.CustomerName = "Jagadish P"; // Through property it will update cust_name (executes "set")
64. 
65.            //Using property, we are going to retrieve/get the value in cust_name
66.            Console.WriteLine("Name after updatation : {0}", a.CustomerName); //executes "get"
67.  
68.            // Using "Balance" property we are going to change the value in "bal"
69.            a.Balance = 200;   //executes "set"
70.            Console.WriteLine("Balance after updation is : {0}", a.GetBalance());
71.  
72.            /*Balance property cannot be used to display/retrieve, since it doesn't contain "get"(WriteOnly)
73.             Console.WriteLine("Balance after updation is : {0}", a.balance());
74.              
75.             If you try to attempt, the error would be as follows:
76. 
77.             Error  1   The property or indexer 'Properties.BankAccount.balance' cannot be used in this context because it lacks the get accessor   D:\CodeCentral\Properties\Properties\Program.cs 62  25  Properties*/
78.  
79.        }
80.    }
81.}

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following