Home

The Properties of a Class

 

Properties Fundamentals

 

Introduction

When creating the member variables of a class, you usually create fields as private members. This makes sure that a field is not accessible outside of the class so that the clients of the class cannot directly influence its value. If you create a member variable as private but still want other classes to access or get the value of such a field, you must then create one or two "accessories".

 

Practical LearningPractical Learning: Introducing Properties

  1. Start Microsoft Visual Studio or Microsoft Visual Web Developer
  2. To start creating a web site, on the main menu, click File -> New -> Web Site... (or File -> New Web Site...)
  3. Set the name of the web site to cpap1
  4. Make sure the Language is set to Visual C# and click OK
  5. To create a new class, on the main menu, click Website -> Add New Item...
  6. In the Templates list, click Class
  7. Change the Name to AutoPart and click Add
  8. Read the message box asking you to store the class in an App_Code folder that will be created and click Yes
  9. Change the class as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for AutoPart
    /// </summary>
    public class AutoPart
    {
        private long partNbr;
        private int yr;
        private string mk;
        private string mdl;
        private string nm;
        private double prc;
    
        public AutoPart()
        {
        }
    }
  10. Save the file

Accessories for Properties

A property is a member of a class that plays an intermediary role to a field of the class. A property is used to "filter" access to a field of a class. Therefore, you start by declaring a private field. Here is an example:

<script runat="server">
public class Square
{
    private double _side;
}
</script>

Obviously this private field cannot be accessed by an outside class. To let the outside classes access this variable, you would/can create a property. To create a property, you must create a member whose formula resembles a method without the parentheses. Since or if the property will be accessed by only by objects of the same program, you can mark it with the internal keyword. If the property will be accessed by objects of this and other programs, you should mark it as public. Therefore, you would start a property as follows:

<script runat="server">
public class Square
{
    private double _side;

    // This is a new property
    public double Side
    {
    }
}
</script>

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

Practical LearningPractical Learning: Creating Properties

  1. To create a property for each member variable, change the class as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for AutoPart
    /// </summary>
    public class AutoPart
    {
        private long partNbr;
        private int yr;
        private string mk;
        private string mdl;
        private string nm;
        private double prc;
    
        public AutoPart()
        {
        }
    
        // This property represents the part number of an auto part
        public long PartNumber
        {
        }
    
        // This property represents the year of a car
        public int Year
        {
        }
    
        // This property represents a car make
        public string Make
        {
        }
    
        // This property represents a car model
        public string Model
        {
        }
    
        // This property represents the name or description of an auto part
        public string Name
        {
        }
    
        // A property for the marked price of an item
        public double UnitPrice
        {
        }
    }
  2. 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 keyword, using the traditional curly brackets that delimit a section of code. Here is an example:

<script runat="server">
public class Square
{
    private double _side;

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

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

<script runat="server">
public class Square
{
    private double _side;

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

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:

<script runat="server">
public class Square
{
    private double _side;

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

    public Square(double s)
    {
        _side = s;
    }
}
</script>

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

<%@ Page Language="C#" %>
<html>
<head>

<script runat="server">
public class Square
{
    private double _side;

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

    public Square(double s)
    {
        _side = s;
    }
}
</script>

<title>Exercise</title>
</head>
<body>

<%
    Square sq = new Square(-25.55);

    Response.Write("Square Side: " + sq.Side.ToString());
%>

</body>
</html>

This would produce:

Square

You can create a conditional statement in the read property to perform a checking process. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>

<script runat="server">
public class Square
{
    private double _side;

    // This is a new property
    public double Side
    {
        get
        {
            // If the value given to the side is negative,
            // then set it to 0
            if (_side < 0)
                return 0;
            else
                return _side;
        }
    }

    public Square(double s)
    {
        _side = s;
    }
}
</script>

<title>Exercise</title>
</head>
<body>

<%
    Square sq1 = new Square(-12.48);
    Square sq2 = new Square(25.55);

    Response.Write("<pre>First Square Characteristics<br />");
    Response.Write("Side:      " + sq1.Side.ToString() + "</pre>");

    Response.Write("<pre>Second Square Characteristicss<br />");
    Response.Write("Side:      " + sq2.Side.ToString() + "</pre>");
%>

</body>
</html>

This would produce:

Square

Practical Learning Practical Learning: Creating Property Readers

  1. To create read properties, change the class as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for AutoPart
    /// </summary>
    public class AutoPart
    {
        private long partNbr;
        private int yr;
        private string mk;
        private string mdl;
        private string nm;
        private double prc;
    
        // This is the default constructor, used for an undefined auto part
        public AutoPart()
        {
            partNbr = 0;
            yr = 1960;
            mk = "Unknown";
            mdl = "Unknown";
            nm = "Not available";
            prc = 0.00;
        }
    
        // This constructor is used to create or define an auto part
        public AutoPart(long number, int carYear,
                        string carMake, string carModel,
                        string partDescription, double autoPartPrice)
        {
            partNbr = number;
            yr = carYear;
            mk = carMake;
            mdl = carModel;
            nm = partDescription;
            prc = autoPartPrice;
        }
    
        // This property represents the part number of an auto part
        public long PartNumber
        {
            get
            {
                return partNbr;
            }
        }
    
        // This property represents the year of a car
        public int Year
        {
            get
            {
                return yr;
            }
        }
    
        // This property represents a car make
        public string Make
        {
            get
            {
                return mk;
            }
        }
    
        // This property represents a car model
        public string Model
        {
            get
            {
                return mdl;
            }
        }
    
        // This property represents the name or description of an auto part
        public string Name
        {
            get
            {
                return nm;
            }
        }
    
        // A property for the marked price of an item
        public double UnitPrice
        {
            get
            {
                return prc;
            }
        }
    }
  2. Save the file 
 
 
 

Property Writers

A property is referred to as write if it can change (or write) the value of its corresponding field. To create a write property, type the set keyword followed by the curly bracket delimiters. Here is an example:

<script runat="server">
public class Square
{
    private double _side;

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

The minimum assignment you can perform with a write property is to assign it a value that would be provided by the outside world. To support this, C# provides the value contextual keyword (contextual means the word is a keyword only in some cases, depending on how it is being used). Here is an example:

<script runat="server">
public class Square
{
    private double _side;

    // This is a new property
    public double Side
    {
        set
        {
            _side = value;
        }
    }
}
</script>

Clients of a class can change the corresponding field of a member variable through the property writer. Consider the following code:

<%@ Page Language="C#" %>
<html>
<head>

<script runat="server">
public class Square
{
    public double _side;

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

    public Square()
    {
        _side = 0;
    }

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

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

    public double Area()
    {
        return _side * _side;
    }
}
</script>

<title>Exercise</title>
</head>
<body>

<%
    Square sq1 = new Square();
    Square sq2 = new Square();

    sq1._side = -12.48;
    sq2._side = 25.55;

    Response.Write("<pre>First Square Characteristics<br />");
    Response.Write("Side:      " + sq1._side.ToString() + "<br />");
    Response.Write("Perimeter: " + sq1.Perimeter().ToString() + "<br />");
    Response.Write("Area:      " + sq1.Area().ToString() + "</pre>");

    Response.Write("<pre>Second Square Characteristics<br />");
    Response.Write("Side:      " + sq2._side.ToString() + "<br />");
    Response.Write("Perimeter: " + sq2.Perimeter().ToString() + "<br />");
    Response.Write("Area:      " + sq2.Area().ToString() + "</pre>");
%>

</body>
</html>

Here is an example of testing the code:

Square

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 field.

Read/Write Properties

If you create a property that has only a set section, the property is referred to as write-only. 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. Such a property is referred to as read/write.

Practical Learning Practical Learning: Creating Property Writers

  1. To create read/write properties, change the class as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for AutoPart
    /// </summary>
    public class AutoPart
    {
        private long partNbr;
        private int yr;
        private string mk;
        private string mdl;
        private string nm;
        private double prc;
    
        // This is the default constructor, used for an undefined auto part
    	public AutoPart()
    	{
            partNbr = 0;
            yr = 1960;
            mk = "Unknown";
            mdl = "Unknown";
            nm = "Not available";
            prc = 0.00;
        }
    
        // This constructor is used to create or define an auto part
        public AutoPart(long number, int carYear,
                        string carMake, string carModel,
                        string partDescription, double autoPartPrice)
        {
            partNbr = number;
            yr = carYear;
            mk = carMake;
            mdl = carModel;
            nm = partDescription;
            prc = autoPartPrice;
        }
    
        // This property represents the part number of an auto part
        public long PartNumber
        {
            get
            {
                return partNbr;
            }
    
            set
            {
                if (partNbr < 0 )
                    partNbr = 0;
                else
                    partNbr = value;
            }
        }
    
        // This property represents the year of a car
        public int Year
        {
            get
            {
                return yr;
            }
    
            set
            {
                if (yr < 1960)
                    yr = 1960;
                else
                    yr = value;
            }
        }
    
        // This property represents a car make
        public string Make
        {
            get
            {
                return mk;
            }
            set
            {
                if (mk == "")
                    mk = "Unknown car make";
                else
                    mk = value;
            }
        }
    
        // This property represents a car model
        public string Model
        {
            get
            {
                return mdl;
            }
            set
            {
                if (mdl == "")
                    mdl = "Unknown car model";
                else
                    mdl = value;
            }
        }
    
        // This property represents the name or description of an auto part
        public string Name
        {
            get
            {
                return nm;
            }
            set
            {
                if (nm == "")
                    nm = "Unknown auto part";
                else
                    nm = value;
            }
        }
    
        // A property for the marked price of an item
        public double UnitPrice
        {
            get
            {
                return prc;
            }
    
            set {
                if (prc < 0.00)
                    prc = 0.00;
                else
                    prc = value;
            }
        }
    }
  2. In the Solution Explorer, right-click Default.aspx and click Rename
  3. Type index.aspx to change the name of the home file as follows:

Properties of External Classes

 

Properties and Enumerations

An enumeration is a technique of creating a data type that mimics an integer. After creating it, you can treat it as a pseudo data type. To create an enumeration property, you use the same formula as one of the primitive data types we have used previously.

Here is an example: 

<script runat="server">
public enum ItemCategory
{
    Unspecified,
    Women,
    Men,
    Girls,
    Boys,
    Babies
}

class ShoppingItem
{
        private long itemNo;
        private ItemCategory cat;
        private string nm;
        private string sz;
        private decimal price;

        // A property for the stock number of an item
        public long ItemNumber
        {
            get
            {
                return itemNo;
            }

            set
            {
                if (itemNo <= 0)
                    itemNo = 0;
                else
                    itemNo = value;
            }
        }

        // A property for the category of item
        public ItemCategory Category
        {
            get
            {
                return cat;
            }

            set
            {
                cat = value;
            }
        }

        // A property for the name of an item
        public string Name
        {
            get
            {
                return nm;
            }

            set
            {
                if (nm == "")
                    nm = "Item no Description";
                else
                    nm = value;
            }
        }

        // A property for size of a merchandise
        public string Size
        {
            get
            {
                if( sz == "0" )
                    return "Unknown Size or Fits All";
                else
                    return sz;
            }

            set
            {
                sz = value;
            }
        }

        // A property for the marked price of an item
        public decimal UnitPrice
        {
            get
            {
                return price;
            }

            set
            {
                if (price < 0)
                    price = 0.00M;
                else
                    price = value;
            }
        }
    }
}
</script>

A Class as a Property

Remember that, after creating a class, it becomes a data type in its own right. Here is an example of such a class:

<script runat="server">
public enum ItemCategory
{
    Unspecified,
    Women,
    Men,
    Girls,
    Boys,
    Babies
}

public class ShoppingItem
{
    private long itemNo;
    private ItemCategory cat;
    private string nm;
    private string sz;
    private decimal price;

    // A property for the stock number of an item
    public long ItemNumber
    {
            get
            {
                return itemNo;
            }

            set
            {
                itemNo = value;
            }
    }

    // A property for the category of item
    public ItemCategory Category
    {
            get
            {
                return cat;
            }

            set
            {
                cat = value;
            }
    }

    // A property for the name of an item
    public string Name
    {
            get
            {
                return nm;
            }

            set
            {
                if (nm == "")
                    nm = "Item no Description";
                else
                    nm = value;
            }
    }

    // A property for size of a merchandise
    public string Size
    {
            get
            {
                if (sz == "0")
                    return "Unknown Size or Fits All";
                else
                    return sz;
            }

            set
            {
                sz = value;
            }
    }

    // A property for the marked price of an item
    public decimal UnitPrice
    {
        get
        {
            return price;
        }

        set
        {
            if (price < 0)
                price = 0.00M;
            else
                price = value;
        }
    }
}
</script>

To create a property that is based on a class, primarily follow the same formulas we have applied to the other properties.

Here is an example  :

<script runat="server">

public class DepartmentStore
{
    private int qty;
    private ShoppingItem itm;

    public int Quantity
    {
        get { return qty; }
        set
        {
                if (qty <= 0)
                    qty = 0;
                else
                    qty = value;
        }
    }

    public ShoppingItem SaleItem
    {
        get { return itm; }
        set
        {
                if (itm == null)
                {
                    itm.ItemNumber = 0;
                    itm.Category = ItemCategory.Unspecified;
                    itm.Name = "Unknown";
                    itm.Size = "0";
                    itm.UnitPrice = 0.00M;
                }
                else 
                    itm = value;
        }
    }

    public DepartmentStore()
    {
        itm = new ShoppingItem();
    }
}
</script>
 

 

   
 

Previous Copyright © 2009-2015, FunctionX, Inc. Next