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:
using System;
namespace Example
{
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 Example
{
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 can access it, for example they
can read its value as follows:
using System;
namespace Example
{
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 field, preventing those outside
classes 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 field as private, you can use the read property
to reset the value of the field 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 Example
{
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: Creating Property Readers |
|
- To create read properties, change the contents of the
ShoppingStore.cs file as
follows:
using System;
namespace DepartmentStore2
{
class ShoppingItem
{
private long itemNo;
private string nm;
private string sz;
private decimal price;
// A property for the stock number of an item
public long ItemNumber
{
get
{
return itemNo;
}
}
// A property for the name of an item
public string Name
{
get
{
return nm;
}
}
// A property for size of a merchandise
public string Size
{
get
{
if( sz == "0" )
return "Unknown Size or Fits All";
else
return sz;
}
}
// A property for the marked price of an item
public decimal UnitPrice
{
get
{
return price;
}
}
// A constructor used to initialize an item
public ShoppingItem(long nbr,
string nme,
string siz,
decimal prc)
{
itemNo = nbr;
nm = nme;
sz = siz;
price = prc;
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
namespace DepartmentStore2
{
class Program
{
static void Main()
{
long number;
string name;
string size;
decimal price;
Console.WriteLine("/-/Arrington Department Store/-/");
Console.Write("Enter the Item #: ");
number = long.Parse(Console.ReadLine());
Console.Write("Enter the Item Name: ");
name = Console.ReadLine();
Console.Write("Enter the Item Size: ");
size = Console.ReadLine();
Console.Write("Enter the Unit Price: ");
price = decimal.Parse(Console.ReadLine());
ShoppingItem store = new ShoppingItem(number, name, size, price);
Console.WriteLine("\n================================");
Console.WriteLine("/-/Arrington Department Store/-/");
Console.WriteLine("--------------------------------");
Console.WriteLine("Customer Invoice");
Console.WriteLine("Item #: {0}", store.ItemNumber);
Console.WriteLine("Description: {0}", store.Name);
Console.WriteLine("Item Size: {0}", store.Size);
Console.WriteLine("Unit Price: {0:C}", store.UnitPrice);
Console.WriteLine("================================\n");
}
}
}
|
- Execute the program:
/-/Arrington Department Store/-/
Enter the Item #: 622805
Enter the Item Name: Black Leather Hand Bag
Enter the Item Size: Medium
Enter the Unit Price: 85.95
================================
/-/Arrington Department Store/-/
--------------------------------
Customer Invoice
Item #: 622805
Description: Black Leather Hand Bag
Item Size: Medium
Unit Price: $85.95
================================
Press any key to continue . . .
|
|
- Close the DOS window
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 field 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 field. To
solve this kind of problem, you must provide another means of accessing
the field any time to change its value.
Besides, or instead of, retrieving the value of a
field 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
field 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 field.
|
|
To create a write property, type the set keyword
followed by the curly bracket delimiters. Here is an example:
using System;
namespace Example
{
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 provided by the outside
world. To support this, C# provides the value contextual keyword. Here is an
example:
using System;
namespace Example
{
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 field 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 field. For example, an
external object can assign an invalid value to a member variable. Consider
the following program:
using System;
namespace Example
{
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 field. Remember that the
client objects of the class can only read the value of the field 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 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. Such a property is referred to as read/write.
|
|
Practical
Learning: Creating Property Writers |
|
- To create property writers and complete the program, change the
content of the ShoppingItem.cs file as follows:
using System;
namespace DepartmentStore2
{
class ShoppingItem
{
private long itemNo;
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 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;
}
}
public static ShoppingItem Read()
{
ShoppingItem shop = new ShoppingItem();
Console.Write("Item #: ");
shop.itemNo = long.Parse(Console.ReadLine());
Console.Write("Item Name: ");
shop.Name = Console.ReadLine();
Console.Write("Item Size (Enter 0 if unknown): ");
shop.Size = Console.ReadLine();
Console.Write("Unit Price: ");
shop.UnitPrice = decimal.Parse(Console.ReadLine());
return shop;
}
public static void Write(ShoppingItem item)
{
Console.WriteLine("Item #: {0}", item.ItemNumber);
Console.WriteLine("Description: {0}", item.Name);
Console.WriteLine("Item Size: {0}", item.Size);
Console.WriteLine("Unit Price: {0:C}", item.UnitPrice);
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
namespace DepartmentStore2
{
class Program
{
static void Main()
{
Console.WriteLine("/-/Arrington Department Store/-/");
Console.Write("Enter the following pieces of ");
Console.WriteLine("information about the sale item");
ShoppingItem saleItem = ShoppingItem.Read();
Console.WriteLine("\n================================");
Console.WriteLine("/-/Arrington Department Store/-/");
Console.WriteLine("--------------------------------");
ShoppingItem.Write(saleItem);
}
}
}
|
- Execute the program. Here is an example:
/-/Arrington Department Store/-/
Enter the following pieces of
information about the sale item
Item #: 114888
Item Name: North Hook Alpine Jacket
Item Size (Enter 0 if unknown): Large
Unit Price: 275.95
================================
/-/Arrington Department Store/-/
--------------------------------
Item #: 114888
Description: North Hook Alpine Jacket
Item Size: Large
Unit Price: $275.95
Press any key to continue . . .
|
|
- Close the DOS window
You can create a property as a Boolean type. To do this,
first specify its data type as bool. When treating the property, make
sure its get accessory returns a Boolean type. A Boolean property is not
like the other regular properties. It must specify its value as true or false.
As done for Boolean methods, a Boolean property must produce only a true or
false value.
|
|