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 functions to access or get the value of such a member variable, you must then create one or two functions used as "accessories", like a door in which the external functions or classes must pass through to access the member variable.

 

Accessories for Properties

A property is a member of a class that plays 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 functions or classes that need the salary must present their requests to. As such, these external functions 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.

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 CSharpLessons
{
    public class Square
    {
	private double _side;
    }

    public class Exercise
    {
	static void Main()
	{

	}
    }
}

Obviously this private member variable cannot be accessed by a function or class outside of its class. Therefore, to let outside classes access this variable, you would/can create a property. Unlike Managed C++ and the VCL (Borland C++ Builder and Delphi) where you use a keyword to indicate that you are creating a property, in C#, to create a property, there is a syntax you must follow. To start, you must create a member whose formula resembles a function without the parentheses. Therefore, you would start a property as follows:

using System;

namespace CSharpLessons
{
    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 Microsoft Visual C# or Visual Studio .NET
  2. On the main menu, click File -> New -> Project
  3. If necessary, in the Project Types list of the New Project dialog box, click Visual C# Projects
  4. In the Templates list, click Empty Project
  5. In the Name text box, replace the name with DeptStore3 and specify the desired path in the Location
  6. Click OK
  7. To create a source file for the project, on the main menu, click Project -> Add New Item...
  8. In the Add New Item dialog box, in the Templates list, click Code File
  9. In the Name text box, delete the suggested name and replace it with Exercise
  10. Click Open
  11. In the empty file, type the following:
     
    using System;
    
    namespace CSharpLessons
    {
        public class DepartmentStore
        {
    	private string itemNo;
    	private string cat;
    	private string name;
    	private string size;
    	private double price;
        }
    
        public class Exercise
        {
    	static void Main()
    	{
    
    	}
        }
    }
  12. To execute the application, on the main menu, click Debug -> Start Without Debugging
  13. Return to Visual C#

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 keyword, using the traditional curly brackets that delimit a section of code. Here is an example:

using System;

namespace CSharpLessons
{
    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 CSharpLessons
{
    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 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 CSharpLessons
{
    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 functions can access it, for example they read its value as follows:

using System;

namespace CSharpLessons
{
    public class Square
    {
	private double _side;

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

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

    class Exercise
    {
	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 function to mess with 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 CSharpLessons
{
    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 Exercise
    {
	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

  1. To create read properties, change the contents of the file as follows:
     
    using System;
    
    namespace CSharpLessons
    {
        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. Execute the program
  3. Return to Visual C#
 

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 CSharpLessons
{
    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 CSharpLessons
{
    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 CSharpLessons
{
    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 Exercise
    {
        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 functions 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 CSharpLessons
    {
        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. 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>
  3. Close the Command Prompt
 

Previous Copyright © 2004-2012, FunctionX Next