Home

The Properties of a Class

 

Overview of Properties

 

Introduction

In C++ and Java, when creating member variables of a class, programmers usually "hide" these members in private sections (C++) or create them as private (Java). This technique makes sure that a member variable is not accessed outside the class so that the clients of the class cannot directly influence the value of the member variable. If you create a member variable as private but still want other classes or methods to access or get the value of such a member variable, you must then create one or two methods used as "accessories", like a door in which the external methods or classes must pass through to access the member variable.

A property is a member of a class that acts as an intermediary to a member variable of the class. For example, if you have a member variable of class and that member represents the salary of an employee, a property can be the "door" that other methods or classes that need the salary must present their requests to. As such, these external methods and class cannot just change the salary or retrieve it as they wish. A property can be used to validate their request, to reject or to accept them.

Accessories for Properties

As mentioned already, a property is used to "filter" access to a member variable of a class. Therefore, you start by declaring a (private (if you don't make it private, you may be deceiving the purpose of creating a property)) member variable:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;
    }

    public class Applied
    {
	static void Main()
	{

	}
    }
}

Obviously this private member variable cannot be accessed by a method or class outside of its class. Therefore, to let outside classes access this variable, you would/can create a property.  To create a property, start with a member whose formula resembles a method without the parentheses. Here is an example:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;

        // This is a new property
        public double Side
        {
        }
    }
}

With regards to their role, there are two types of properties.

 

Practical Learning Practical Learning: Introducing Properties

  1. Start a new file in Notepad
  2. From what we know so far, type the following:
     
    using System;
    
    namespace LamackEnterprises
    {
        public class DepartmentStore
        {
    	private string itemNo;
    	private string cat;
    	private string name;
    	private string size;
    	private double price;
        }
    
        public class Exercise
        {
    	static void Main()
    	{
    
    	}
        }
    }
  3. Save it as exercise.cs in a new folder named DeptStore3 inside of your CSharp Lessons folder
  4. To create a property for each member variable, change the DepartmentStore class as follows:
     
    using System;
    
    namespace LamackEnterprises
    {
        public class DepartmentStore
        {
    	private string itemNo;
    	private string cat;
    	private string name;
    	private string size;
    	private double price;
    
            // A property for the stock number of an item
            public string ItemNumber
            {
            }
    
            // A property for the category of item
            public string Category
            {
            }
    
            // A property for an item's name of an item
            public string ItemName
            {
            }
    
            // A property for size of a merchandise
            public string Size
            {
            }
    
            // A property for the marked price of an item
            public double UnitPrice
            {
            }
        }
    
        public class Exercise
        {
    	static void Main()
    	{
    
    	}
        }
    }
  5. Save the file

Types of Properties

 

Property Readers

A property is referred to as read if its role is only to make available the value of the member variable it represents. To create a read property, in the body of the property, type the get keyword and create a body for the property, using the traditional curly brackets that delimit a section of code. Here is an example:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;

        // This is a new property
        public double Side
        {
            get
            {
            }
        }
    }
}

In the body of the get clause, you can implement the behavior that would be used to make the member variable's value available outside. The simplest way consists of just returning the corresponding member variable. Here is an example:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;

        // This is a new property
        public double Side
        {
            get
            {
                return _side;
            }
        }
    }
}

A read property is also referred to as a read-only property because the clients of the class can only retrieve the value of the property but they cannot change it. Therefore, if you create (only) a read property, you should provide the users with the ability to primarily specify the value of the member variable. To do this, you can create an accessory method or a constructor for the class . Here is an example of such a constructor:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;

        // This is a new property
        public double Side
        {
            get
            {
                return _side;
            }
        }

        public Square(double s)
        {
            _side = s;
        }
    }
}

Once a read property has been created, other classes or methods can access it, for example they read its value as follows:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;

        // This is a new property
        public double Side
        {
            get
            {
                return _side;
            }
        }

        public Square(double s)
        {
            _side = s;
        }
    }

    class Applied
    {
	static void Main()
	{
            Square sq = new Square(-25.55);

            Console.WriteLine("Square Side: {0}", sq.Side);

	}
    }
}

This would produce:

Square Side: -25.55

Press any key to continue

We described a property as serving as a door from outside to its corresponding member variable, preventing those outside classes or method to alter the member variable. Notice that the Square class was given a negative value for the member variable, which is usually unrealistic for the side of a square. In this case and others, while still protecting the member variable as private, you can use the read property to reset the value of the member variable or even to reject it. To provide this functionality, you can create a conditional statement in the read property to perform a checking process. Here is an example:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;

        // This is a new property
        public double Side
        {
            get
            {
	if( _side < 0 )
	    return 0;
                // else is implied
                return _side;
            }
        }

        public Square(double s)
        {
            _side = s;
        }
    }

    class Applied
    {
	static void Main()
	{
            Square sq1 = new Square(-12.48);
            Square sq2 = new Square(25.55);

	   Console.WriteLine("First Square Characteristics");
            Console.WriteLine("Side:      {0}\n", sq1.Side);			

            Console.WriteLine("Second Square Characteristics");
	   Console.WriteLine("Side:      {0}\n", sq2.Side);
	}
    }
}

This would produce:

First Square Characteristics
Side:      0

Second Square Characteristics
Side:      25.55
 
 

Practical Learning Practical Learning: Creating Property Readers

Men Khaki Pants Sahara Women Suit Gallantry Girls Satin Dress
Item: Men Khaki Pants Sahara
Sizes: 28, 29, 30, 31, 32, 34
Price: 24.95
Item: Women Suit Gallantry
Sizes:   8, 9-3/4, 10-1/4
Price:  $225.75
Item: Girls Satin Dress
Sizes: 8, 10, 12
Price: 55.95 
Nylon Shoulder Handbag Hat Bluebells Visor Men Puppy Shoes
Item: Nylon Shoulder Handbag
Price: 34.95
Item: Hat Bluebells Visor
Price: 125.95
Item: Men Puppy Shoes
Sizes: 8, 8.50 -> 14.50
Price: 65.75
  1. To create read properties, change the contents of the file as follows:
     
    using System;
    
    namespace LamackEnterprises
    {
        public class DepartmentStore
        {
    	private string itemNo;
    	private string cat;
    	private string name;
    	private string size;
    	private double price;
    
            // A property for the stock number of an item
            public string ItemNumber
            {
                get
                {
                    if( itemNo == "" )
                        return "Invalid Item";
                    else
                        return itemNo;
                }
            }
    
            // A property for the category of item
            public string Category
            {
                get
                {
                    if( cat == "" )
                        return "Unknown Category";
                    else
                        return cat;
                }
            }
    
            // A property for an item's name of an item
            public string ItemName
            {
                get
                {
                    if( name == "" )
                        return "Item no Description";
                    else
                        return name;
                }
            }
    
            // A property for size of a merchandise
            public string Size
            {
                get
                {
                    if( size == "" )
                        return "Unknown Size or Fits All";
                    else
                        return size;
                }
            }
    
            // A property for the marked price of an item
            public double UnitPrice
            {
                get
                {
                    if( price == 0 )
                        return 0.00;
                    else
                        return price;
                }
            }
           
            public DepartmentStore(string nbr,
                                   string ctg,
                                   string nme,
                                   string siz,
                                   double prc)
            {
                itemNo = nbr;
                cat    = ctg;
                name   = nme;
                size   = siz;
                price  = prc;
            }
    
        }
    
        public class Exercise
        {
    	static void Main()
    	{
                DepartmentStore store = new DepartmentStore("53564",
                                                            "Men",
                                                            "Khaki Pants Sahara",
                                                            "34",
                                                            24.95);
                int quantity = 4;
                double totalPrice = store.UnitPrice * quantity;
    
                Console.WriteLine("Customer Invoice");
                Console.WriteLine("Item #:      {0}", store.ItemNumber);
                Console.WriteLine("Category:    {0}", store.Category);
                Console.WriteLine("Description: {0}", store.ItemName);
                Console.WriteLine("Item Size:   {0}", store.Size);
                Console.WriteLine("Unit Price:  {0}", store.UnitPrice.ToString("C"));
                Console.WriteLine("Quantity:    {0}", quantity);
                Console.WriteLine("Total Price: {0}\n", totalPrice.ToString("C"));
    	}
        }
    }
  2. Save the file and open the Command Prompt to the folder that contains the current exercise
  3. Compile and execute the program:
     
  4. Return to your text editor

Property Writers

In our Square class so far, we were using a constructor to create a value for each of the necessary member variables. This meant that we had to always make sure that we knew the value of the member variable when we declared an instance of the class. Sometimes, this is not effective. For example, you cannot just call a constructor in the middle of the program, that is after the object has been declared, to assign a new value to the member variable. To solve this kind of problem, you must provide another means of accessing the member variable any time to change its value.

Besides, or instead of, retrieving the value of a member variable of a class, you may want external classes to be able to change the value of that member. Continuing with our policy to hide a member variable as private, you can create another type of property. A property is referred to as write if it can change (or write) the value of its corresponding member variable.

To create a write property, type the set keyword followed by the curly bracket delimiters. Here is an example:

using System;

namespace Geometry
{
    public class Square
    {
        private double _side;

        // This is a new property
        public double Side
        {
	    set
	    {
	    }
        }
    }
}

The minimum assignment you can perform with a write property is to assign it a value that would be provide by the outside world. To support this, C# provides the value keyword. Here is an example:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;

        // This is a new property
        public double Side
        {
	    set
	    {
                 	_side = value
	    }
        }
    }
}

As you see, clients of a class can change the corresponding member variable of a member variable through the property writer. Based on this relationship, it is not unusual for a client of a class to make an attempt to "mess" with a member variable. For example, an external object can assign an invalid value to a member variable. Consider the following program:

using System;

namespace Geometry
{
    public class Square
    {
	private double _side;

        // This is a new property
        public double Side
        {
            get
            {
                return _side;
            }

            set
           {
                _side = value;
           }
        }

        public Square(double s)
        {
            _side = s;
        }

        public double Perimeter()
       {
            return Side * 4;
       }

       public double Area()
       {
            return Side * Side;
       }
    }

    class Applied
    {
        static void Main()
       {
            Square sq1 = new Square();
            Square sq2 = new Square();
			
            sq1.Side = -12.48;
            sq2.Side = 25.55;

            Console.WriteLine("First Square Characteristics");
            Console.WriteLine("Side:      {0}", sq1.Side);
            Console.WriteLine("Perimeter: {0}", sq1.Perimeter());
            Console.WriteLine("Area:      {0}\n", sq1.Area());

            Console.WriteLine("Second Square Characteristics");
            Console.WriteLine("Side:      {0}", sq2.Side);
            Console.WriteLine("Perimeter: {0}", sq2.Perimeter());
            Console.WriteLine("Area:      {0}", sq2.Area());
        }
    }
}

This would produce:

First Square Characteristics
Side:      -12.48
Perimeter: -49.92
Area:      155.7504

Second Square Characteristics
Side:      25.55
Perimeter: 102.2
Area:      652.8025

Press any key to continue

Because of this, and since it is through the writer that the external objects would change the value of the member variable, you can use the write property, rather than the reader, to validate or reject a new value assigned to the member variable. Remember that the client objects of the class can only read the value of the member variable through the read property. Therefore, there may be only little concern on that side.

If you create a property that has only a set section, the property is referred to as write-only because the other classes or methods can only assign it a value (or write a value to it). If you create a property that has both a get and a set sections, its corresponding member variable can receive new values from outside the class and the member variable can provide its values to clients of the class.

 

Practical Learning Practical Learning: Creating Property Writers

  1. To create property writers and complete the program, change the content of the file as follows:
     
    using System;
    
    namespace LamackEnterprises
    {
        public class DepartmentStore
        {
    	private string itemNo;
    	private string cat;
    	private string name;
    	private string size;
    	private double price;
    
    	// A property for the stock number of an item
    	public string ItemNumber
    	{
                get
    	    {
    		return itemNo;
    	    }
    
                set
    	    {
    		if( itemNo == "" )
    	            itemNo = "Invalid Item";
    		else
    	            itemNo = value;
                }
    	}
    
    	// A property for the category of item
    	public string Category
    	{
                get
    	    {
    		return cat;
    	    }
    
                set
    	    {
    		if( cat == "" )
    	            cat = "Unknown Category";
    		else
    	            cat = value;
    	    }
    	}
    
    	// A property for an item's name of an item
    	public string ItemName
    	{
                 get
    	    {
    		return name;
    	    }
    
                 set
    	    {
    		if( name == null )
    	            name = "Item no Description";
    		else
    	            name = value;
                }       
    	}
    
    	// A property for size of a merchandise
    	public string Size
    	{
                 get
    	    {
    		return size;
    	    }
    
                 set
    	    {
    		if( size == null )
    	            size = "Unknown Size or Fits All";
    		else
    	            size = value;
                }       
    	}
    
    	// A property for the marked price of an item
     	public double UnitPrice
    	{
                 get
    	    {
    		return price;
    	    }
    
                 set
    	    {
    		if( price < 0 )
    	            price = 0.00;
    		else
    	            price = value;
    	    }        
    	}
        }     
    
        public class Exercise
        {
    	static void Main()
    	{
                int quantity = 0;
    	   DepartmentStore item1 = new DepartmentStore();
                double totalPrice = 0;
    
                item1.ItemNumber = "G76-85";
    	   item1.ItemName   = "Men Something";
    	   item1.Size       = "36L28W";
    	   quantity         = 6;
    	   totalPrice = item1.UnitPrice * quantity;
    
                Console.WriteLine("Customer Invoice - Bad Receipt");
    	   Console.WriteLine("Item #:      {0}", item1.ItemNumber);
    	   Console.WriteLine("Category:    {0}", item1.Category);
                Console.WriteLine("Description: {0}", item1.ItemName);
    	   Console.WriteLine("Item Size:   {0}", item1.Size);
    	   Console.WriteLine("Unit Price:  {0}", item1.UnitPrice.ToString("C"));
    	   Console.WriteLine("Quantity:    {0}", quantity);
    	   Console.WriteLine("Total Price: {0}\n", totalPrice.ToString("C"));
    
                item1.ItemNumber = "74797";
    	   item1.Category   = "Women";
    	   item1.ItemName   = "Suit Gallantry";
    	   item1.Size       = "10-1/4";
    	   item1.UnitPrice  = 225.75;
                quantity         = 2;
    	   totalPrice = item1.UnitPrice * quantity;
    
                Console.WriteLine("Customer Invoice - 12/08/2002");
                Console.WriteLine("Item #:      {0}", item1.ItemNumber);
                Console.WriteLine("Category:    {0}", item1.Category);
    	   Console.WriteLine("Description: {0}", item1.ItemName);
    	   Console.WriteLine("Item Size:   {0}", item1.Size);
                Console.WriteLine("Unit Price:  {0}", item1.UnitPrice.ToString("C"));
    	   Console.WriteLine("Quantity:    {0}", quantity);
    	   Console.WriteLine("Total Price: {0}\n", totalPrice.ToString("C"));
    	}
        }
    }
  2. Close the file. When asked whether you want to save it, click Yes
  3. Switch to the Command Prompt
  4. Compile and execute the program:
     
    C:\CSharp Lessons\DeptStore3>csc exercise.cs
    Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
    for Microsoft (R) .NET Framework version 1.1.4322
    Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.
    
    
    C:\CSharp Lessons\DeptStore3>exercise
    Customer Invoice - Bad Receipt
    Item #:      G76-85
    Category:
    Description: Item no Description
    Item Size:   Unknown Size or Fits All
    Unit Price:  $0.00
    Quantity:    6
    Total Price: $0.00
    
    Customer Invoice - 12/08/2002
    Item #:      74797
    Category:    Women
    Description: Suit Gallantry
    Item Size:   10-1/4
    Unit Price:  $225.75
    Quantity:    2
    Total Price: $451.50
    
    
    C:\CSharp Lessons\DeptStore3>
  5. Close the Command Prompt
 

Previous Copyright 2004-2006 FunctionX, Inc. Next