Topics on Using the Objects of a Class
Topics on Using the Objects of a Class
Techniques of Creating and Using a Constructor
A Constructor with No Body
As mentioned for methods, if you are creating a small constructor that contains a single statement, you can replace the curly brackets with the => operator after the parentheses of the name of the constructor. This is followed by the necessary one-line statement.
Practical Learning: Creating and Using a Read-Only Field
namespace Geometry03
{
class EquilateralTriangle
{
private double s;
const double NumberOfSides = 3;
public EquilateralTriangle()
{
s = 0;
}
public EquilateralTriangle(double side)
{
s = side;
}
public double CalculatePerimeter()
{
double dResult = 0;
dResult = s * NumberOfSides;
return dResult;
}
}
}
Control | (Name) | Text |
Label | Side: | |
TextBox | txtSide | 0.00 |
Button | Calculate | btnCalculate |
Label | Perimeter: | |
TextBox | txtPerimeter | TextAlign: Right |
using System;
using System.Windows.Forms;
namespace Geometry03
{
public partial class Form1 : Form
{
public Geometry()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
EquilateralTriangle et = new EquilateralTriangle();
double side = double.Parse(txtSide.Text);
et = new EquilateralTriangle(side);
txtPerimeter.Text = et.CalculatePerimeter().ToString();
}
}
}
namespace Geometry03 { class EquilateralTriangle { private double s; const double NumberOfSides = 3; public EquilateralTriangle() => s = 0; public EquilateralTriangle(double side) => s = side; public double CalculatePerimeter() => s * NumberOfSides; } }
When creating a field of a class, one of the decisions you must make is how the field would get its value(s). To create a field so that objects outside the class can only view its value but cannot change it while the value can be changed inside the class, create that field as read-only. To do this, when creating the field in the class, precede its data type with the readonly keyword. Here is an example:
public class Circle
{
readonly double PI;
}
You can mark the field with an access level such as private or public, depending on your intentions.
To specify the value of a read-only field, use a constructor, such as the default constructor, to initialize the field. Here is an example:
public class Circle { private double r; private readonly double PI; public Circle() { PI = 3.14; } }
Only of the differences between a constant variable and a read-only field is that a constant variable must be initialized when creating it. On the other hand, you can create more than one constructor in a class, then assign the same or a different value in each constructor to the read-only field. This means that, because you can initialize a read-only field in a constructor, if you have different constructors, you can also have different values for the same read-only field.Here are examples:
public class Circle { private double r; private readonly double PI; public Circle() { PI = 3.14; } public Circle(double rad) { r = rad; PI = 3.14159; } public double CalculateDiameter() { return r * 2; } public double CalculateArea() { return r * r * PI; } }
Instead of a constant value, the value of a read-only field can come from an expression. If the value held by a read-only field is gotten from an expression, then the field must be initialized in the(a) construction with the desired expression.
We know that a constant variable must be initialized when it is created. Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don't need to initialize a read-only variable when you declare it since you can do this in the(a) constructor of the class. Also, because a constructor can be overloaded, a read-only field can hold different values depending on the particular constructor that is accessed at a particular time, but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).
Practical Learning: Creating and Using a Read-Only Field
namespace Geometry04
{
class Circle
{
public readonly double PI = 3.14;
public double Radius;
public Circle()
{
Radius = 0.00;
}
public double CalculateDiameter()
{
return Radius * 2.00;
}
public double CalculateArea()
{
return Radius * Radius * PI;
}
}
}
Control | (Name) | Text |
Label | Radius: | |
TextBox | txtRadius | 0.00 |
Button | btnCalculate | Calculate |
Label | Diameter: | |
TextBox | txtDiameter | |
Label | Area: | |
TextBox | txtArea |
using System;
using System.Windows.Forms;
namespace Geometry04
{
public partial class Form1 : Form
{
public Geometry()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
Circle round = new Circle();
round.Radius = double.Parse(txtRadius.Text);
txtDiameter.Text = round.CalculateDiameter().ToString();
txtArea.Text = round.CalculateArea().ToString();
}
}
}
namespace Geometry04
{
class Circle
{
public readonly double PI;
public double Radius;
public Circle()
{
PI = 3.14;
Radius = 0.00;
}
public double CalculateDiameter()
{
return Radius * 2.00;
}
public double CalculateArea()
{
return Radius * Radius * PI;
}
}
}
Control | (Name) | Text |
Label | PI: | |
TextBox | txtPI |
using System;
using System.Windows.Forms;
namespace Geometry04
{
public partial class Form1 : Form
{
public Geometry()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
Circle round = new Circle();
round.Radius = double.Parse(txtRadius.Text);
txtPI.Text = round.PI.ToString();
txtDiameter.Text = round.CalculateDiameter().ToString();
txtArea.Text = round.CalculateArea().ToString();
}
}
}
namespace Geometry04
{
class Circle
{
public readonly double PI;
public double Radius;
public Circle()
{
PI = 3.14;
Radius = 0.00;
}
public Circle(double rad)
{
Radius = rad;
PI = 3.14159;
}
public double CalculateDiameter()
{
return Radius * 2.00;
}
public double CalculateArea()
{
return Radius * Radius * PI;
}
}
}
using System;
using System.Windows.Forms;
namespace Geometry04
{
public partial class Form1 : Form
{
public Geometry()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
Circle round = new Circle(double.Parse(txtRadius.Text));
txtPI.Text = round.PI.ToString();
txtDiameter.Text = round.CalculateDiameter().ToString();
txtArea.Text = round.CalculateArea().ToString();
}
}
}
A Field of a Class Type
Just like a primitive type can be used to describe an object, a class can play that role too. To make this happen, create a member that uses a class as its type. You can use any class, including one you create yourself. Here is an example:
class Rectangle
{
public double Width;
public double Height;
}
class Box
{
Rectangle Face;
}
You can mark the field with an access level such as private, public or internal, etc.
A Field with the Same Type and Name
A field of a class type can use the same name as the class. Here is an example:
class Employee
{
}
class TimeSheet
{
private double timeWorked;
private string filingStatus;
public Employee Employee;
}
In this case, the compiler would know that the first name represents a type and the second name represents a field. In the methods of the class, when you use the name as variable, the compiler would know that you are accessing the field.
Of course, the class can also have members of any type. Here is an example:
public class Rectangle
{
public double Width;
public double Height;
}
public class Box
{
public double Depth;
public Rectangle Face;
}
If a member of a class A (for example, the above Box class) is of a class type B (for example, the above Rectangle class):
public class Rectangle
{
public double Width;
public double Height;
}
public class Box
{
public double Depth;
public Rectangle Face = new Rectangle();
}
public class Rectangle
{
public double Width;
public double Height;
}
public class Box
{
public double Depth;
public Rectangle Face;
public void Initialize()
{
Face = new Rectangle();
}
}
If you use this technique, make sure you call that method before using the member. This can be done as follows:
public class Exercise
{
private void Describe()
{
Box rectangular = new Box();
rectangular.Initialize();
}
}
public class Rectangle
{
public double Width;
public double Height;
}
public class Box
{
public double Depth;
public Rectangle Face;
public void Initialize()
{
Face = new Rectangle();
}
}
public class Exercise
{
private void Describe()
{
Box rectangular = new Box();
rectangular.Face = new Rectangle();
}
}
public class Rectangle
{
public double Width;
public double Height;
}
public class Box
{
public double Depth;
public Rectangle Face;
}
Practical Learning: Using a Field as a Class Type
namespace Geometry05 { class Rectangle { public double Width; public double Height; } }
namespace Geometry05 { class Box { public double Depth; public Rectangle Face; } }
Control | (Name) | Text |
Label | Width: | |
TextBox | txtWidth | 0.00 |
Label | Height | |
TextBox | txtHeight | 0.00 |
Label | Depth | |
TextBox | txtDepth | 0.00 |
Button | btnCalculate | Calculate |
Label | Front/Back: | |
TextBox | txtFrontBack | |
Label | Left/Right | |
TextBox | txtLeftRight | |
Label | Top/Bottom | |
TextBox | txtTopBottom |
using System;
using System.Windows.Forms;
namespace Geometry05
{
public partial class Form1 : Form
{
public Geometry()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
Box rectangular = new Box();
rectangular.Face = new Rectangle();
double width = double.Parse(txtWidth.Text);
double height = double.Parse(txtHeight.Text);
double depth = double.Parse(txtDepth.Text);
rectangular.Face.Width = width;
rectangular.Face.Height = height;
rectangular.Depth = depth;
double frontBackPerimeter = (rectangular.Face.Width + rectangular.Face.Height) * 2;
double leftRightPerimeter = (rectangular.Face.Height + rectangular.Depth) * 2;
double topBottomPerimeter = (rectangular.Face.Width + rectangular.Depth) * 2;
txtFrontBack.Text = frontBackPerimeter.ToString();
txtLeftRight.Text = leftRightPerimeter.ToString();
txtTopBottom.Text = topBottomPerimeter.ToString();
}
}
}
Control | (Name) | Text |
Label | Symbol: | |
TextBox | txtSymbol | |
Label | Element Name: | |
TextBox | txtElementName | |
Label | Atomic Number: | |
TextBox | txtAtomicNumber | |
Label | Atomic Weight: | |
TextBox | txtAtomicWeight |
namespace Chemistry02
{
public class Element
{
internal string ElementName;
internal string Symbol;
internal int AtomicNumber;
internal double AtomicWeight;
public Element()
{
}
public Element(int number)
{
AtomicNumber = number;
}
public Element(string symbol)
{
Symbol = symbol;
}
public Element(int number, string symbol, string name, double mass)
{
Symbol = symbol;
ElementName = name;
AtomicWeight = mass;
AtomicNumber = number;
}
}
}
Introduction to Classes and Objects
A Class Type as Parameter
An object of a class can be passed as argument. For example, a class type can be used as a parameter of a method of another class. When creating the method, simply provide the name of a class as type followed by a name for the parameter. You can use a class from the .NET Framework or your own class. As mentioned already, in the body of the method, you can ignore or use the parameter. When it comes to a class passed as parameter, its public and internal members are available to the method that uses it. When calling the method, you must provide an object created from the class.
Classes are always used as references. This means that, when using a class as parameter, it is implied to be passed by reference. If you want to reinforce this, you can type the ref keyword to the left of the parameter and when passing the argument.
Instead of one parameter, a method can use as many parameters as you want. The parameters can be of the same or different types, and you can use a combination of classes and primitive types.
Practical Learning: Returning an Object
using System.Windows.Forms;
namespace Chemistry02
{
public partial class Form1 : Form
{
public Chemistry()
{
InitializeComponent();
Element h = new Element(1, "H", "Hydrogen", 1.008);
Element he = new Element(2, "He", "Helium", 4.002602);
Element li = new Element(3, "Li", "Lithium", 6.94);
Element be = new Element(4, "Be", "Beryllium", 9.0121831);
Element b = new Element(5, "B", "Boron", 10.81);
Element o = new Element(number: 8, symbol: "O", mass: 15.999, name: "Oxygen");
Element c = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
Element n = new Element(7);
n.Symbol = "N";
n.AtomicWeight = 14.007;
n.ElementName = "Nitrogen";
Present(o);
}
void Present(Element obj)
{
txtElementName.Text = obj.ElementName;
txtSymbol.Text = obj.Symbol;
txtAtomicNumber.Text = obj.AtomicNumber.ToString();
txtAtomicWeight.Text = obj.AtomicWeight.ToString();
}
}
}
Returning an Object
A method can be made to produce an object. When creating the method, specify the name of the desired class before the name of the method. You can use your own class or use one of the many classes that come with the .NET Framework. In the body of the method, you can declare a variable of the class and initialize it. Before the closing bracket of the method, you must use the return keyword followed by the object and a semicolon. Here is an example:
public class Square { private double s; public Square(double side) { s = side; } public double CalculatePerimeter() { return s * 4; } public double CalculateArea() { return s * s; } } public class Plate { private Square Create() { Square sqr = new Square(10); . . . Blah Blah Blah return sqr; } }
Calling a Method that Returns an Object
To call a method that returns an object, you can first declare a variable of the class's return type and later assign the method call to it. Here is an example:
public class Square { private double s; public Square(double side) { s = side; } } public class Plate { private Square Create() { Square sqr = new Square(10M); . . . Blah Blah Blah return sqr; } private void Describe() { Square s = new Square(0m); . . . Blah Blah Blah s = Create(); } }
Since the method internally initializes the object, you don't have to initialize the receiving variable. This means that you can directly assign the method call to it. Here is an example:
public class Square
{
private double s;
public Square(double side)
{
s = side;
}
public double CalculatePerimeter()
{
return s * 4;
}
public double CalculateArea()
{
return s * s;
}
}
public class Plate
{
private Square Create()
{
Square sqr = new Square(10M);
return sqr;
}
private void Describe()
{
Square s = Create();
}
}
Practical Learning: Returning an Object
using System.Windows.Forms; namespace Chemistry02 { public partial class Form1 : Form { public Chemistry() { InitializeComponent(); Element elm = Prepare(); Present(elm); } void Present(Element obj) { txtElementName.Text = obj.ElementName; txtSymbol.Text = obj.Symbol; txtAtomicNumber.Text = obj.AtomicNumber.ToString(); txtAtomicWeight.Text = obj.AtomicWeight.ToString(); } Element Prepare() { Element h = new Element(1, "H", "Hydrogen", 1.008); Element he = new Element(2, "He", "Helium", 4.002602); Element li = new Element(3, "Li", "Lithium", 6.94); Element f = new Element(number: 9, symbol: "F", mass: 18.998403163, name: "Fluorine"); Element be = new Element(4, "Be", "Beryllium", 9.0121831); Element b = new Element(5, "B", "Boron", 10.81); Element c = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6); Element n = new Element(7); n.Symbol = "N"; n.AtomicWeight = 14.007; n.ElementName = "Nitrogen"; Element o = new Element(number: 8, symbol: "O", mass: 15.999, name: "Oxygen"); return f; } } }
Returning an Object From a Class's Own Method
You can create a method that returns an instance of its own class. To start, on the left side of the method, enter the name of the class. Here is an example:
public class Employee
{
public Employee Create()
{
}
}
There are various ways you can deal with the method. If you want to return a new value of the class, you can declare an instance of the class, initialize it, and then return it. Here is an example:
public class Employee
{
public int EmplNbr;
public string FName;
public string LName;
public double Salary;
public Employee Create()
{
Employee staff = new Employee();
staff.EmplNbr = 947059;
staff.FName = "Paull";
staff.LName = "Motto";
staff.Salary = 54925;
return staff;
}
}
Another technique consists of declaring an instance of the class and initialize its fields with those of the class. Here is an example:
public class Employee
{
public int EmplNbr;
public string FName;
public string LName;
public double Salary;
public Employee Create()
{
Employee staff = new Employee();
staff.EmplNbr = EmplNbr;
staff.FName = FName;
staff.LName = LName;
staff.Salary = Salary;
return staff;
}
}
Most of the time, this technique may not be very useful. As an alternative, you can pass some parameters to the method and then initialize the fields of the class with those parameters. After doing this, when calling the method, you can assign it to an object of the same class.
Practical Learning: Introducing the Returned Object
Control | (Name) | Text |
Label | Electric Meter | |
Label | _______________________________ | |
Label | Meter #: | |
TextBox | txtMeterNumber | |
Label | Make: | |
TextBox | txtMake | |
Label | Model: | |
TextBox | txtModel | |
Button | btnShowMeterDetails | Show Meter Details |
Label | Meter Details | |
TextBox | txtMeterDetails | |
Label | ======================= | |
Label | Customer Charges | |
Label | _______________________________ | |
Label | Customer Charge: | |
TextBox | txtCustomerCharge | |
Label | Delivery Tax Rate: | |
TextBox | txtDeliveryTaxRate | |
Label | % | |
Label | Grid Resilience Charge Rate: | |
TextBox | txtGridResilienceChargeRate | |
Label | Environment Surcharge Rate: | |
TextBox | txtEnvironmentSurchargeRate | |
Label | ======================= | |
Button | Bill Summary | |
Label | _______________________________ | |
Label | Total Use: | |
TextBox | txtTotalUse | |
Label | Delivery Taxes: | |
TextBox | txtDeliveryTaxes | |
Label | Energy Charges: | |
TextBox | txtEnergyCharges | |
Label | Grid Resilience Charge: | |
TextBox | txtGridResilienceCharge | |
Label | Environment Surcharge: | |
TextBox | txtEnvironmentSurcharge | |
Label | Amount Due: | |
TextBox | txtAmountDue |
Using the Returned Object of a Method
Consider the following class created in a file named BillPreparation.cs. This section will be practically studied in a narrative format.
Practical Learning: Using the Returned Object of a Method
namespace ElectricityDistribution1 { // Eletricity Distribution Company public class Meter { public string MeterNumber; public string Make; public string Model; public string Describe() { string details = Make + " " + Model + " (Mtr #: " + MeterNumber + ")"; return details; } } }
using System;
using System.Windows.Forms;
namespace ElectricityDistribution1
{
public partial class Form1 : Form
{
public BillProcessing()
{
InitializeComponent();
}
private void btnShowMeterDetails_Click(object sender, EventArgs e)
{
Meter mtr = new Meter();
mtr.MeterNumber = txtMeterNumber.Text;
mtr.Make = txtMake.Text;
mtr.Model = txtModel.Text;
txtMeterDetails.Text = mtr.Describe();
}
}
}
Meter #: FGL-6048 Make: Thiesen Power Model; KV-2604
namespace ElectricityDistribution1
{
// Eletricity Distribution Company
public class Meter
{
public string MeterNumber;
public string Make;
public string Model;
public string Describe()
{
string details = Make + " " + Model + " (Mtr #: " + MeterNumber + ")";
return details;
}
}
public class CounterReading
{
private Meter mtr;
public int TotalUse;
public CounterReading()
{
mtr = new Meter();
}
public Meter Read()
{
return mtr;
}
}
}
using System; using System.Windows.Forms; namespace ElectricityDistribution1 { public partial class Form1 : Form { public BillProcessing() { InitializeComponent(); } private void btnShowMeterDetails_Click(object sender, EventArgs e) { CounterReading cr = new CounterReading(); Meter mtr = cr.Read(); mtr.MeterNumber = txtMeterNumber.Text; mtr.Make = txtMake.Text; mtr.Model = txtModel.Text; txtMeterDetails.Text = mtr.Describe(); } } }
Meter #: WEJ-9284 Make: Pepperus Worldwide Model; i2024
namespace ElectricityDistribution1
{
// Eletricity Distribution Company
public class Meter
{
public string MeterNumber;
public string Make;
public string Model;
public string Describe()
{
return Make + " " + Model + " (Mtr #: " + MeterNumber + ")";
}
}
public class CounterReading
{
private Meter mtr;
public int TotalUse;
public CounterReading()
{
mtr = new Meter();
}
public Meter Read()
{
return mtr;
}
}
public class Calculations
{
public CounterReading Useage;
public Calculations()
{
Useage = new CounterReading();
}
public CounterReading Prepare()
{
return Useage;
}
}
}
using System; using System.Windows.Forms; namespace ElectricityDistribution1 { public partial class Form1 : Form { public BillProcessing() { InitializeComponent(); } private void btnShowMeterDetails_Click(object sender, EventArgs e) { Calculations cals = new Calculations(); CounterReading cr = cals.Prepare(); Meter mtr = cr.Read(); mtr.MeterNumber = txtMeterNumber.Text; mtr.Make = txtMake.Text; mtr.Model = txtModel.Text; txtMeterDetails.Text = mtr.Describe(); } } }
Meter #: KBV-9728 Make: Frellatta International Model; G2806T
When you call a method that returns an object, the call holds an actual value of the class. As a result, you can call the method directly where the object is needed. If the class of that object contains a method that returns an object you need, you can call that other method directly after the parentheses of the previously mentioned method. For many examples, first click the BillPreparation.cs tab and change the document as follows:
namespace ElectricityDistribution1 { // Eletricity Distribution Company public class Meter { public string MeterNumber; public string Make; public string Model; public string Describe() => Make + " " + Model + " (Mtr #: " + MeterNumber + ")"; } public class CounterReading { private Meter mtr; public int TotalUse; public CounterReading() { mtr = new Meter(); mtr.Make = "Horriander"; mtr.Model = "CXL 3600"; mtr.MeterNumber = "M927084"; } public Meter Read() => mtr; } public class Calculations { public CounterReading Useage; public const double CustomerCharge = 7.60; public const double DeliveryTaxRate = 6.20; public const double EnergyChargeRate = 6.2655; public const double GridResilienceChargeRate = 12; public const double EnvironmentSurchargeRate = 14.90; public Calculations() { Useage = new CounterReading(); Useage.TotalUse = 1497; } public double CalculateEnergyCharges() { return Useage.TotalUse * EnergyChargeRate / 100; } public double CalculateGridResilienceCharges() { return Useage.TotalUse * GridResilienceChargeRate / 100000; } public double CalculateDeliveryTaxes() { return Useage.TotalUse * DeliveryTaxRate / 10000; } public double CalculateEnvironmentalSurcharge() { return Useage.TotalUse * EnvironmentSurchargeRate / 100000; } public double EvaluateAmountDue() { return CustomerCharge + CalculateEnergyCharges() + CalculateGridResilienceCharges() + CalculateDeliveryTaxes() + CalculateEnvironmentalSurcharge(); } public CounterReading Prepare() { return Useage; } } public class ElectriBill { private Calculations values; public ElectriBill() { values = new Calculations(); } public Calculations Prepare() { return values; } } }
using System;
using System.Windows.Forms;
namespace ElectricityDistribution1
{
public partial class Form1 : Form
{
public BillProcessing()
{
InitializeComponent();
ElectriBill eb = new ElectriBill();
txtMeterNumber.Text = eb.Prepare().Useage.Read().MeterNumber;
txtMake.Text = eb.Prepare().Useage.Read().Make;
txtModel.Text = eb.Prepare().Useage.Read().Model;
txtMeterDetails.Text = eb.Prepare().Prepare().Read().Describe();
txtCustomerCharge.Text = Calculations.CustomerCharge.ToString("F");
txtDeliveryTaxRate.Text = Calculations.DeliveryTaxRate.ToString("F");
txtEnergyChargeRate.Text = Calculations.EnergyChargeRate.ToString("F");
txtGridResilienceChargeRate.Text = Calculations.GridResilienceChargeRate.ToString("F");
txtEnvironmentSurchargeRate.Text = Calculations.EnvironmentSurchargeRate.ToString("F");
txtTotalUse.Text = eb.Prepare().Useage.TotalUse.ToString();
txtEnvironmentalSurcharge.Text = eb.Prepare().CalculateEnvironmentalSurcharge().ToString("F");
txtDeliveryTaxes.Text = eb.Prepare().CalculateDeliveryTaxes().ToString("F");
txtGridResilienceCharges.Text = eb.Prepare().CalculateGridResilienceCharges().ToString("F");
txtEnergyCharges.Text = eb.Prepare().CalculateEnergyCharges().ToString("f");
txtAmountDue.Text = eb.Prepare().EvaluateAmountDue().ToString("F");
}
private void btnShowMeterDetails_Click(object sender, EventArgs e)
{
}
}
}
Of course, you can apply the same technique if the code is written inside the method of a class. Here is an example:
// Eletricity Distribution Company
public class Meter
{
public string MeterNumber;
public string Make;
public string Model;
public string Describe() => MeterNumber + " (" + Make + ", " + Model + ")";
}
public class CounterReading
{
private Meter mtr;
public int TotalUse;
public CounterReading()
{
mtr = new Meter();
mtr.Make = "Horriander";
mtr.Model = "CXL 3600";
mtr.MeterNumber = "M927084";
}
public Meter Read() => mtr;
}
public class Calculations
{
public CounterReading Useage;
const double CustomerCharge = 7.60;
const double DeliveryTaxRate = 6.20;
const double EnergyChargeRate = 6.2655;
const double GridResilienceChargeRate = 12;
const double EnvironmentSurchargeRate = 14.90;
public Calculations()
{
Useage = new CounterReading();
Useage.TotalUse = 1497;
}
public double CalculateEnergyCharges() => Useage.TotalUse * EnergyChargeRate / 100;
public double CalculateGridResilienceCharges() => Useage.TotalUse * GridResilienceChargeRate / 100000;
public double CalculateDeliveryTaxes() => Useage.TotalUse * DeliveryTaxRate / 10000;
public double CalculateEnvironmentalSurcharge() => Useage.TotalUse * EnvironmentSurchargeRate / 100000;
public double EvaluateAmountDue()
{
return CustomerCharge +
CalculateEnergyCharges() +
CalculateGridResilienceCharges() +
CalculateDeliveryTaxes() +
CalculateEnvironmentalSurcharge();
}
public CounterReading Prepare() => Useage;
}
public class ElectriBill
{
private Calculations values;
public ElectriBill()
{
values = new Calculations();
}
public Calculations Calculate()
{
return values;
}
public string Summarize()
{
string strSummary = values.Prepare().Read().Describe();
return strSummary;
}
}
Here is code that uses the result
ElectriBill eb = new ElectriBill(); Meter Nbr: eb.Summarize() Amount Due: eb.Calculate().EvaluateAmountDue().ToString("F")
To make your code easier to read, you can put each call on its own line. Here is an example:
// Eletricity Distribution Company
public class Meter
{
public string MeterNumber;
public string Make;
public string Model;
public string Describe() => MeterNumber + " (" + Make + ", " + Model + ")";
}
public class CounterReading
{
private Meter mtr;
public int TotalUse;
public CounterReading()
{
mtr = new Meter();
mtr.Make = "Horriander";
mtr.Model = "CXL 3600";
mtr.MeterNumber = "M927084";
}
public Meter Read() => mtr;
}
public class Calculations
{
public CounterReading Useage;
const double CustomerCharge = 7.60;
const double DeliveryTaxRate = 6.20;
const double EnergyChargeRate = 6.2655;
const double GridResilienceChargeRate = 12;
const double EnvironmentSurchargeRate = 14.90;
public Calculations()
{
Useage = new CounterReading();
Useage.TotalUse = 1497;
}
public double CalculateEnergyCharges() => Useage.TotalUse * EnergyChargeRate / 100;
public double CalculateGridResilienceCharges() => Useage.TotalUse * GridResilienceChargeRate / 100000;
public double CalculateDeliveryTaxes() => Useage.TotalUse * DeliveryTaxRate / 10000;
public double CalculateEnvironmentalSurcharge() => Useage.TotalUse * EnvironmentSurchargeRate / 100000;
public double EvaluateAmountDue()
{
return CustomerCharge +
CalculateEnergyCharges() +
CalculateGridResilienceCharges() +
CalculateDeliveryTaxes() +
CalculateEnvironmentalSurcharge();
}
public CounterReading Prepare() => Useage;
}
public class ElectriBill
{
private Calculations values;
public ElectriBill() => new Calculations();
public Calculations Calculate() => values;
public string Summarize()
{
string strSummary = values.Prepare()
.Read()
.Describe();
return strSummary;
}
}
Passing a Class in, and Returning an Object from, its Own Method
In a class, you can create a method that both uses a parameter that is of the type of its own class and returns an object that is the type of its own class. Here is an example:
public class Circle { public Circle Create(Circle cir) { } }
As mentioned already, in the body of the method, the parameter has access to all members of the class. Before exiting the method, make sure you return an object that is the type of the class. Here is an example:
public class Circle
{
public Circle Create(Circle cir)
{
Circle rounder = new Circle();
return rounder;
}
}
Involving a Class in its Own Members
The Type of a Field as its Own Class
In a class, you can create a field that is the type of its own class. Here is an example:
public class Employee { public int EmplNbr; public string FName; public string LName; public double Salary; Employee staff; }
If you do this, the field can be accessed by any member of the same class. If you make the field public or internal, if you decide to use it outside the class, you can access the public and internal members of the class through that field.
Passing a Class Type to its Own Method
An instance of a class can be passed as an argument to one of its own methods. To do this, you primarily pass the argument as if it were any type. Here is an example:
public class HotelRoom
{
public void Display(HotelRoom room)
{
}
}
In the body of the method, you can do whatever you want. You can, or you may not, use the parameter. Still, if you decide to use the parameter, know that all of the other members of the class are accessible through the parameter. One of the simplest ways you can use the parameter is the assign each of of its values to the equivalent member of the class. Here is an example:
public class HotelRoom
{
private string RoomNumber;
private int Capacity;
private string RoomType;
private double BaseRate;
public void Display(HotelRoom room)
{
RoomNumber = room.RoomNumber;
Capacity = room.Capacity;
RoomType = room.RoomType;
BaseRate = room.BaseRate;
}
}
When calling the method, make sure you pass an instance of the class to it. You can first create and define an object of the class, then pass it.
A Class Type as a Parameter to its Own Constructor
Just like a class can be used as the type of a parameter in one of its own methods, a class type can be used as a parameter to one of its own constructors. This can be done as follows:
public class HotelRoom
{
public HotelRoom(HotelRoom sample)
{
}
}
Instead of a formal method, you can use a constructor of the class to pass an instance of the same class. Then, in the constructor, use the argument as you see fit, knowing that all the members of the class are available.
Returning an Object From a Class's Own Method
You can create a method that returns an instance of its own class. To start, on the left side of the method, enter the name of the class. Here is an example:
public class Employee
{
public Employee Create()
{
}
}
There are various ways you can deal with the method. If you want to return a new value of the class, you can declare an instance of the class, initialize it, and then return it. Here is an example:
public class Employee
{
public int EmplNbr;
public string FName;
public string LName;
public double Salary;
public Employee Create()
{
Employee staff = new Employee();
staff.EmplNbr = 947059;
staff.FName = "Paull";
staff.LName = "Motto";
staff.Salary = 54925;
return staff;
}
}
Another technique consists of declaring an instance of the class and initialize its fields with those of the class. Here is an example:
public class Employee
{
public int EmplNbr;
public string FName;
public string LName;
public double Salary;
public Employee Create()
{
Employee staff = new Employee();
staff.EmplNbr = EmplNbr;
staff.FName = FName;
staff.LName = LName;
staff.Salary = Salary;
return staff;
}
}
Most of the time, this technique may not be very useful. As an alternative, you can pass some parameters to the method and then initialize the fields of the class with those parameters. After doing this, when calling the method, you can assign it to an object of the same class.
Passing a Class in, and Returning an Object from, its Own Method
In a class, you can create a method that both uses a parameter that is of the type of its own class and returns an object that is the type of its own class. Here is an example:
public class Circle { public Circle Create(Circle cir) { } }
As mentioned already, in the body of the method, the parameter has access to all members of the class. Before exiting the method, make sure you return an object that is the type of the class. Here is an example:
public class Circle
{
public Circle Create(Circle cir)
{
Circle rounder = new Circle();
return rounder;
}
}
Using a Reference of a Class Without its Object
Introduction
So far, to create an object, we had to declare a variable of the desired class. A variable, or object, is necessary only if you are planning to use the object more than once. If you need a reference to the object only once (or just a few times), you don't need a variable. In this case, in the section of code where you want the reference, simply type the new keyword followed by the name of the class. Since you are calling a constructor of the class, you must add parentheses.
public class Triangle
{
public double Width;
public double Depth;
public double CalculateArea() => Width * Depth / 2.00;
}
. . .
new Triangle();
Passing a Reference to a Method
Consider the following class:
public class Triangle { public double Width; public double Depth; public Triangle(double w, double d) { Width = w; Depth = d; } public double CalculateArea() => Width * Depth / 2.00; }
In order to use an object, you usually first declare a variable of the class before calling the method that needs it. If you are not planning to use the object many times, you don't have to first declare a variable for it. You can pass the initialization directly to the method. Here is an example:
double width = 0.00, height = 0.00, area = 0.00;
width = double.Parse(txtWidth.Text);
height = Request["txtWidth"].Asdouble();
area = new Triangle(width, height).CalculateArea();
Returning a Reference
As done for a value of a regular type, you can return an object value from a method of a class. To do this, you can first declare the method and specify the class as the return type. Here is an example:
public class Triangle
{
public double Width;
public double Depth;
public Triangle(double w, double d)
{
Width = w;
Depth = d;
}
public double CalculateArea() => Width * Depth / 2.00;
}
public class Shape
{
private Triangle Create()
{
double width = 2834.208;
double depth = 602.415;
return new Triangle(width, depth);
}
}
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2021, C# Key | Next |
|