Topics on Properties
Topics on Properties
Processing a Property
Introduction
A property is a good place to perform calculations. One of the differences between a method (or function) is that a property doesn't take a parameter. As a result, if you want a property to use values external to the class, you must find a way to make such values available to the property. One way to solve this problem is to create or use a method in the class. The value used by a property can be of a primitive type or of another class.
Practical Learning: Procesing a Property
namespace PieceWork5.Models { public class DayWork { private double _sal_; private int _tires_; private double baseDailyPay; public void Initialize(int tires, double hRate, double payRate) { _tires_ = tires; _sal_ = payRate; baseDailyPay = hRate * 8.00; } public double NetPay { get { double payFromWork = _sal_ * _tires_; if (payFromWork <= baseDailyPay) return baseDailyPay; else return payFromWork; } } } }
using PieceWork5.Models; using static System.Console; WriteLine("Tires Corner"); WriteLine("==================================================="); WriteLine("Enter the number of tires installed for each day"); Write("Monday: "); int monTires = int.Parse(ReadLine()); Write("Tuesday: "); int tueTires = int.Parse(ReadLine()); Write("Wednesday: "); int wedTires = int.Parse(ReadLine()); Write("Thursday: "); int thuTires = int.Parse(ReadLine()); Write("Friday: "); int friTires = int.Parse(ReadLine()); WriteLine("---------------------------------------------------"); Write("Hourly Rate: "); double hRate = double.Parse(ReadLine()); Write("Rate Per Tire: "); double ratePerTire = double.Parse(ReadLine()); DayWork dw = new DayWork(); dw.Initialize(monTires, hRate, ratePerTire); double mondayPay = dw.NetPay; dw.Initialize(tueTires, hRate, ratePerTire); double tuesdayPay = dw.NetPay; dw.Initialize(wedTires, hRate, ratePerTire); double wednesdayPay = dw.NetPay; dw.Initialize(thuTires, hRate, ratePerTire); double thursdayPay = dw.NetPay; dw.Initialize(friTires, hRate, ratePerTire); double fridayPay = dw.NetPay; double totalPay = mondayPay + tuesdayPay + wednesdayPay + thursdayPay + fridayPay; WriteLine("==================================================="); WriteLine(" Tires Corner"); WriteLine("---------------------------------------------------"); WriteLine(" Payroll Summary"); WriteLine("==================================================="); WriteLine(" Tires Installed Net Pay"); WriteLine("---------------------------------------------------"); WriteLine("Monday: {0, 6:f} {1, 6:f}", monTires, mondayPay); WriteLine("---------------------------------------------------"); WriteLine("Tuesday: {0, 6:f} {1, 6:f}", tueTires, tuesdayPay); WriteLine("---------------------------------------------------"); WriteLine("Wednesday: {0, 6:f} {1, 6:f}", wedTires, wednesdayPay); WriteLine("---------------------------------------------------"); WriteLine("Thursday: {0, 6:f} {1, 6:f}", thuTires, thursdayPay); WriteLine("---------------------------------------------------"); WriteLine("Friday: {0, 6:f} {1, 6:f}", friTires, fridayPay); WriteLine("==================================================="); WriteLine(" Total Pay: {0, 6:f}", totalPay); Write("===================================================");
Tires Corner =================================================== Enter the number of tires installed for each day Monday: 82 Tuesday: 49 Wednesday: 86 Thursday: 53 Friday: 105 --------------------------------------------------- Hourly Rate: 11.35 Rate Per Tire: 1.22 =================================================== Tires Corner --------------------------------------------------- Payroll Summary =================================================== Tires Installed Net Pay --------------------------------------------------- Monday: 82.00 100.04 --------------------------------------------------- Tuesday: 49.00 90.80 --------------------------------------------------- Wednesday: 86.00 104.92 --------------------------------------------------- Thursday: 53.00 90.80 --------------------------------------------------- Friday: 105.00 128.10 =================================================== Total Pay: 514.66 =================================================== Press any key to close this window . . .
namespace PieceWork5.Models { public class DayWork { private double _sal_; private int _tires_; private double baseDailyPay; public void Initialize(int tires, double hRate, double payRate) { _tires_ = tires; _sal_ = payRate; baseDailyPay = hRate * 8.00; } public double NetPay { get { if( (_sal_ * _tires_) <= baseDailyPay ) return baseDailyPay; else return (_sal_ * _tires_); } } } }
Tires Corner =================================================== Enter the number of tires installed for each day Monday: 73 Tuesday: 88 Wednesday: 55 Thursday: 95 Friday: 47 --------------------------------------------------- Hourly Rate: 10.85 Rate Per Tire: 1.34 =================================================== Tires Corner --------------------------------------------------- Payroll Summary =================================================== Tires Installed Net Pay --------------------------------------------------- Monday: 73.00 97.82 --------------------------------------------------- Tuesday: 88.00 117.92 --------------------------------------------------- Wednesday: 55.00 86.80 --------------------------------------------------- Thursday: 95.00 127.30 --------------------------------------------------- Friday: 47.00 86.80 =================================================== Total Pay: 516.64 =================================================== Press any key to close this window . . .
As you may remember, the ternary operator is used to simplify the code of an if...else conditional statement. You can use the ternary operator to create such a statement in a property.
Practical Learning: Using the Ternary Operator
namespace PieceWork5.Models
{
public class DayWork
{
private double _sal_;
private int _tires_;
private double baseDailyPay;
public void Initialize(int tires, double hRate, double payRate)
{
_tires_ = tires;
_sal_ = payRate;
baseDailyPay = hRate * 8.00;
}
public double NetPay
{
get
{
return ( (_sal_ * _tires_) <= baseDailyPay ) ? baseDailyPay : (_sal_ * _tires_);
}
}
}
}
Tires Corner =================================================== Enter the number of tires installed for each day Monday: 102 Tuesday: 97 Wednesday: 74 Thursday: 68 Friday: 51 --------------------------------------------------- Hourly Rate: 9.75 Rate Per Tire: 1.58 =================================================== Tires Corner --------------------------------------------------- Payroll Summary =================================================== Tires Installed Net Pay --------------------------------------------------- Monday: 102.00 161.16 --------------------------------------------------- Tuesday: 97.00 153.26 --------------------------------------------------- Wednesday: 74.00 116.92 --------------------------------------------------- Thursday: 68.00 107.44 --------------------------------------------------- Friday: 51.00 80.58 =================================================== Total Pay: 619.36 =================================================== Press any key to close this window . . .
Read/Write Properties and Conditional Statements
The purpose of a property is to serve as a relay between the interior of an object and anything that needs to pass a value to it or to receive a value from it. As a result, a property must be able to accept or reject a value that other items (objects, applications, etc) try to submit to its object. A property can also be used to perform calculations on values received from client objects. To take care of these and other situations, you can create one or more conditional statements in both clauses of a read/write property.
Nesting a Function in a Property
In the body of a property, whether a get or a set clause, you can nest a function, which means you can create a function in the body of the clause. You can then call that function right there in the body of the clause. Here is an example of nesting a function in a get clause:
using static System.Console; class Mattress { int _thk; public string Thickness { get { void Show() { WriteLine("The thickness of our mattresses is expressed in pounds."); } string pds = "pounds"; Show(); return _thk; } } }
An Expression-Bodied Property
Another way to reduce the amount of code involved with a property is to create it as an expression-bodied member. In this case, replace the return keyword with the => operator.
Introduction to Automatic Properties
A Read-Only Automatic Property
As you should be aware by now, a read-only property is one that only provides values to external objects that cannot write values to it. To help you easily create an automatic read-only property, the C# language provides a formula as follows:
access-level data-type property-name { get; }
Based on this, to create a read-only property, simply include get; in its curly brackets. Here is an example:
public class Book
{
public string ISBN { get; }
}
By the way, in previous versions of C#, to create a read-only property, you had to add private set; in the curly brackets. Here is an example:
public class Book
{
public string ISBN { get; private set; }
}
A Read-Write Automatic Property
If you want to create a simple read/write property that relays values between a class and the external objects, you don't have to create a local field for it. To help you easily create a property, the C# language provides a formula as follows:
access-level data-type property-name { get; set; }
To use this formula, declare what resembles a variable followed by { get; set; }. This is referred to as an automatic property. Here is an example of an automatic property:
class Rectangle
{
public double Width { get; set; }
}
Of course, a Boolean property can also be created as an automatic property. Here is an example:
public class Member
{
public bool Accepted { get; set; }
}
Practical Learning: Creating Automatic Properties
namespace PlanarCurves2.Models { public class Ellipse { public double radius { get; set; } public double Radius { get; set; } public double Area { get { return Radius * radius * 3.14159265; } } } }
using PlanarCurves2.Models; using static System.Console; Ellipse els = new Ellipse(); WriteLine("========================================="); WriteLine("Enter the values to process the ellipse"); Write("Small Radius: "); double small = double.Parse(ReadLine()); Write("Large Radius: "); double large = double.Parse(ReadLine()); els.radius = small; els.Radius = large; WriteLine("========================================="); WriteLine("Geometry - Ellipse Summary"); WriteLine("-----------------------------------------"); WriteLine("Small Radius: {0}", els.radius); WriteLine("Large Radius: {0}", els.Radius); WriteLine("-----------------------------------------"); WriteLine("Area: {0}", els.Area); WriteLine("=========================================");
========================================= Enter the values to process the ellipse Small Radius: 537.59 Large Radius: 805.73 ========================================= Geometry - Ellipse Summary ----------------------------------------- Small Radius: 537.59 Large Radius: 805.73 ----------------------------------------- Area: 1360788.3669530486 ========================================= Press any key to close this window . . .
A Property of a Class Type
Introduction
After creating a class, it becomes a data type in its own right. As a normal data type, it can be involved in any regular property issue. Of course, to involve a class in a property-related operation, you must first have a class. You can use one an existing class or you can create a new one. To start, we already know how to create a field of a class type. Here is an example:
class Camera { } class TrafficTicket { Camera cmr; }
A Regular Class Type
We already know that, to have a property reader, you can create a get clause that returns the field. Here is an example:
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
private Camera cmr;
public Camera Recorder
{
get
{
return cmr;
}
}
}
In the body of the get clause, we already know that you can create some type of validation for the field (to accept or reject its value), but if you are creating a regular property that simply returns the field, you can make the property as an expression-body. Here is an example:
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
private Camera cmr;
public Camera Recorder
{
get => cmr
}
}
On the other hand, if you want to get a property-writer, create a set clause. In its body, assign value to the field. Here is an example:
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
private Camera cmr;
public Camera Recorder
{
set
{
cmr = value;
}
}
}
We will see that you can process the field value in the set clause. If you are planning to create a simple property that only assigns the property to the value contextual keyword, you can change the body of the set class into an expression-body. Here is an example:
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
Camera cmr;
public Camera Recorder
{
set => cmr = value;
}
}
An Automatic Property of a Class Type
In some cases, you will want to process the members (fields, properties, etc) of the property that is of a class type. In some other cases, you will want a simple property that only represents a characteristic of an object based on the class. In this case, you can make the property automatic. You have various options.
If you want a simple property that only produces an object, you can create the property as an automatic one with only get. Here is an example:
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
public Camera Recorder
{
get;
}
}
If you want a property that only writes an object, create a write-only automatic property.
If you want a simple property that the clients of the class can both read from and write to, you can create the property as an automatic one. Here is an example:
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
public Camera Recorder
{
get;
set;
}
}
Using a Property of a Class Type
Introduction
If you create a property of a value (primitive) type, you can immediately use it. Here is an example:
using static System.Console; public class Employee { public string FullName { get; set; } } public class Exercise { static void Main() { Employee staff = new Employee(); staff.FullName = "Ebalé Mesô Mê Mvuu"; WriteLine("Employee Name: {0}", staff.FullName); } }
This would produce:
Employee Name: Ebalé Mesô Mê Mvuu Press any key to continue . . .
In this case, the (string) property was not initialized in the class where it was created, then that property was accessed and used where needed. If you use a property of a class type directly, you will receive an error. Here is an example:
using static System.Console; public class Camera { public string Location { get; set; } } public class TrafficTicket { public Camera Recorder { get; set; } } public class Exercise { static void Main() { TrafficTicket tt = new TrafficTicket(); tt.Recorder.Location = "Freemont Drive and Winchester Road"; WriteLine("Infraction Location: {0}", tt.Recorder.Location); } }
This would produce:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Exercise.Main(String[] args) in C:\Users\pkatts\Source\Repos\Exercises\Exercises\Exercise.cs:line 22 Press any key to continue . . .
You must first initialize the property. You have many options.
Initializing a Property of a Class Type Before Use
Before using a property of a class, you can first initialize it from an object of the class. Here is an example:
using static System.Console; public class Camera { public string Location { get; set; } } public class TrafficTicket { public Camera Recorder { get; set; } } TrafficTicket tt = new TrafficTicket(); tt.Recorder = new Camera(); tt.Recorder.Location = "Freemont Drive and Winchester Road"; WriteLine("Infraction Location: {0}", tt.Recorder.Location);
This would produce:
Infraction Location: Freemont Drive and Winchester Road Press any key to continue . . .
Initializing a Property of a Class Type When Creating it
Notice that, in the above code, you must remember to initialize the property of a class type before accessing the members of the property. For some reason, you may forget to initialize the property or you may do it wrongly. Probably the best way to get the property of the class type ready is to initialize the property when creating it. To do this, after the closing curly bracket of the property, use the new operator to initialize the property using a constructor of the class type. Here is an example:
using static System.Console;
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
public Camera Recorder
{
get;
set;
} = new Camera();
}
TrafficTicket tt = new TrafficTicket();
tt.Recorder.Location = "Freemont Drive and Winchester Road";
WriteLine("Infraction Location: {0}", tt.Recorder.Location);
Practical Learning: Ending the Lesson
namespace QuatroGas2.Models
{
internal class GasMeter
{
public string MeterNumber { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
}
namespace QuatroGas2.Models
{
internal class Customer
{
public string AccountNumber { get; set; }
public GasMeter GasMeter { get; set; }
public string AccountName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string State { get; set; }
}
}
using QuatroGas2.Models; GasMeter gasMeter = new GasMeter(); gasMeter.MeterNumber = "826-840"; gasMeter.Make = "Polar"; gasMeter.Model = "LL-882"; Customer client = new Customer(); client.AccountNumber = "7938-3796-3749"; client.GasMeter = gasMeter; client.AccountName = "Michael Oliver Hayes"; client.Address = "4941 Powerfelt Street"; client.City = "Felton"; client.County = "Kent"; client.State = "DE"; Console.WriteLine("Quatro Gas"); Console.WriteLine("====================================="); Console.WriteLine("Customer Information"); Console.WriteLine("-------------------------------------"); Console.WriteLine("Account #: {0}", client.AccountNumber); Console.WriteLine("Customer Name: {0}", client.AccountName); Console.WriteLine("Address: {0}", client.Address); Console.WriteLine("City: {0}", client.City); Console.WriteLine("County: {0}", client.County); Console.WriteLine("State: {0}", client.State); Console.WriteLine("====================================="); Console.WriteLine("Customer Gas Meter"); Console.WriteLine("-------------------------------------"); Console.WriteLine("Meter #: {0}", gasMeter.MeterNumber); Console.WriteLine("Make: {0}", gasMeter.Make); Console.WriteLine("Model: {0}", gasMeter.Model); Console.WriteLine("=====================================");
Quatro Gas ===================================== Customer Information ------------------------------------- Account #: 7938-3796-3749 Customer Name: Michael Oliver Hayes Address: 4941 Powerfelt Street City: Felton County: Kent State: DE ===================================== Customer Gas Meter ------------------------------------- Meter #: 826-840 Make: Polar Model: LL-882 ===================================== Press any key to close this window . . .
using QuatroGas2.Models; GasMeter gasMeter = new GasMeter(); gasMeter.MeterNumber = "497-384"; gasMeter.Make = "Saunders"; gasMeter.Model = "404i"; Customer client = new Customer(); client.AccountNumber = "5279-5186-9374"; client.GasMeter = gasMeter; client.AccountName = "Nancy Mitchell"; client.Address = "4706 North Powell Blvd"; client.City = "Quarryville"; client.County = "Lancaster"; client.State = "PA"; Console.WriteLine("Quatro Gas"); Console.WriteLine("====================================="); Console.WriteLine("Customer Information"); Console.WriteLine("-------------------------------------"); Console.WriteLine("Account #: {0}", client.AccountNumber); Console.WriteLine("Customer Name: {0}", client.AccountName); Console.WriteLine("Address: {0}", client.Address); Console.WriteLine("City: {0}", client.City); Console.WriteLine("County: {0}", client.County); Console.WriteLine("State: {0}", client.State); Console.WriteLine("====================================="); Console.WriteLine("Customer Gas Meter"); Console.WriteLine("-------------------------------------"); Console.WriteLine("Meter #: {0}", client.GasMeter.MeterNumber); Console.WriteLine("Make: {0}", client.GasMeter.Make); Console.WriteLine("Model: {0}", client.GasMeter.Model); Console.WriteLine("=====================================");
Quatro Gas ===================================== Customer Information ------------------------------------- Account #: 7938-3796-3749 Customer Name: Michael Oliver Hayes Address: 4941 Powerfelt Street City: Felton County: Kent State: DE ===================================== Customer Gas Meter ------------------------------------- Meter #: 826-840 Make: Polar Model: LL-882 ===================================== Press any key to close this window . . .
using QuatroGas2.Models;
Customer client = new Customer();
client.AccountNumber = "4958-6402-9746";
client.GasMeter = new GasMeter();
client.GasMeter.MeterNumber = "180-700";
client.GasMeter.Make = "Frayers";
client.GasMeter.Model = "D86V";
client.AccountName = "Patricia Francine Barnes";
client.Address = "258 Gainsbrow Court";
client.City = "Columbia";
client.County = "Howard";
client.State = "MD";
Console.WriteLine("Quatro Gas");
Console.WriteLine("============================================");
Console.WriteLine("Customer Information");
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Account #: {0}", client.AccountNumber);
Console.WriteLine("Customer Name: {0}", client.AccountName);
Console.WriteLine("Address: {0}", client.Address);
Console.WriteLine("City: {0}", client.City);
Console.WriteLine("County: {0}", client.County);
Console.WriteLine("State: {0}", client.State);
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Gas Meter Details: {0} - {1} {1}",
client.GasMeter.MeterNumber, client.GasMeter.Make, client.GasMeter.Model);
Console.WriteLine("============================================");
Quatro Gas ============================================ Customer Information -------------------------------------------- Account #: 4958-6402-9746 Customer Name: Patricia Francine Barnes Address: 258 Gainsbrow Court City: Columbia County: Howard State: MD -------------------------------------------- Gas Meter Details: 180-700 - Frayers Frayers ============================================ Press any key to close this window . . .
|
|||
Previous | Copyright © 2001-2023, C# Key | Saturday 29 April 2023 | Next |
|