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.

ApplicationPractical Learning: Creating and Using a Read-Only Field

  1. Start Microsoft Visual Studio
  2. On the Visual Studio 2019 dialog box, in the list of projects templates, click Create a New Project (if Microsoft Visual Studio was already running, on the main menu, click File -> New -> Project...)
  3. In the list of projects templates, click Windows Forms App (.NET Framework)
  4. Click Next
  5. Change the project Name to Geometry03
  6. Click Create
  7. In the Solution Explorer, right-click Geometry02 -> Add -> Class...
  8. Change the name to EquilateralTriangle
  9. Click Add
  10. Right-click in the Code Editor and click Remove and Sort Usings
  11. Change the class as follows:
    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;
            }
        }
    }
  12. In the Solution Explorer, right-click Form1.cs and click Rename
  13. Type Geometry (to get Geometry.cs) and press Enter
  14. Read the message box and press Enter three times (to accept the name and display the form)
  15. Design the form as follows:

    Techniques of Creating and Using a Constructor

    Control (Name) Text
    Label   Side:
    TextBox txtSide 0.00
    Button Calculate btnCalculate
    Label   Perimeter:
    TextBox txtPerimeter TextAlign: Right
  16. Double-click the Calculate button
  17. Right-click in the Code Editor and click Remove and Sort Usings
  18. Implement the event as follows:
    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();
            }
        }
    }
  19. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging:

    Topics on Using the Objects of a Class

  20. In the Side text box, type a number such as 248.73
  21. Click the Calculate button

    Topics on Using the Objects of a Class

  22. Close the form and return to your programming environment
  23. Click the EquilateralTriangle tab to access its class
  24. To create constructors that don't use a body, change the class as follows:
    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;
        }
    }
  25. To execute, press Ctrl + F5
  26. Close the form and return to your programming environment

A Read-Only Field in a Class

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

ApplicationPractical Learning: Creating and Using a Read-Only Field

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the list of projects templates, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the project Name to Geometry04
  5. Click Create
  6. In the Solution Explorer, right-click Geometry04 -> Add -> Class...
  7. Change the name to Circle
  8. Press Enter
  9. Right-click in the Code Editor and click Remove and Sort Usings
  10. Change the class as follows:
    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;
            }
        }
    }
  11. In the Solution Explorer, right-click Form1.cs and click Rename
  12. Type Geometry (to get Geometry.cs) and press Enter
  13. Read the message in the message box and click Yes
  14. In the Solution Explorer, right-click Geometry.cs and click View Designer
  15. Design the form as follows:

    Values Conversion - Metric System

    Control (Name) Text
    Label   Radius:
    TextBox txtRadius 0.00
    Button btnCalculate Calculate
    Label   Diameter:
    TextBox txtDiameter  
    Label   Area:
    TextBox txtArea  
  16. On the form, double-click the Calculated button
  17. Right-click in the Code Editor and click Remove and Sort Usings
  18. Implement the event as follows:
    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();
            }
        }
    }
  19. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Read-Only Fields

  20. In the Side text box, type a number such as 248.73
  21. Click the Calculate button

    Read-Only Fields

  22. Close the browser and return to your programming environment
  23. Click the Circle.cs tab to access the class
  24. You can initialize a read-only field in the (a) constructor of its class. For an example, change the Circle class as follows:
    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;
            }
        }
    }
  25. In the Solution Explorer, right-click Geometry.cs and click View Designer
  26. Change the design of the form as follows:

    Values Conversion - Metric System

    Control (Name) Text
    Label   PI:
    TextBox txtPI  
  27. Double-click the Calculate button
  28. Change the code of the event as follows:
    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();
            }
        }
    }
  29. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Read-Only Fields

  30. In the Side text box, type a number such as 248.73
  31. Click the Calculate button

    Read-Only Fields

  32. Close the browser and return to your programming environment
  33. Click the Circle.cs tab to access the class
  34. Because a read-only field can be initialized in a constructor, each constructor can assign a different value to the field. As a result, a read-only field can have different values. When you create an object, the constructor you choose will provide the value of the read-only field. For examples, change the Circle class as follows:
    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;
            }
        }
    }
  35. Click the Geometry.cs tab to access the code of the form
  36. Change the code of the event as follows:
    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();
            }
        }
    }
  37. To execute the project, on the main menu, click Debug -> Start Without Debugging
  38. In the Side text box, type a number such as 1327.97
  39. Click the button

    Read-Only Fields

  40. Close the browser and return to your programming environment

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):

ApplicationPractical Learning: Using a Field as a Class Type

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the list of projects templates, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the project Name to Geometry05
  5. Click Create
  6. In the Solution Explorer, right-click Geometry04 -> Add -> Class...
  7. Change the code to Rectangle
  8. Click Add
  9. Right-click in the Code Editor and click Remove and Sort Usings
  10. Type the code as follows:
    namespace Geometry05
    {
        class Rectangle
        {
            public double Width;
            public double Height;
        }
    }
  11. In the Solution Explorer, right-click Geometry04 -> Add -> Class...
  12. In the middle list, make sure Class is selected.
    Change the name to Box
  13. Press Enter
  14. Right-click in the Code Editor and click Remove and Sort Usings
  15. Type the code as follows:
    namespace Geometry05
    {
        class Box
        {
            public double Depth;
            public Rectangle Face;
        }
    }
  16. In the Solution Explorer, right-click Form1.cs and click Rename
  17. Type Geometry (to get Geometry.cs) and press Enter
  18. Read the message box and click Yes
  19. In the Solution Explorer, right-click Geometry.cs and click View Designer
  20. Design the form as follows:

    Using a Field as a Class Type

    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  
  21. Doble-click the Calculate button
  22. Right-click in the Code Editor and click Remove and Sort Usings
  23. Implement the event as follows:
    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();
            }
        }
    }
    
  24. To execute the project, on the main menu, click Debug -> Start Without Debugging

    Using a Field as a Class Type

  25. In the Width text box, type a number such as 137.58
  26. In the Height text box, type a number such as 69.33
  27. In the Depth text box, type a number such as 88.97

    Using a Field as a Class Type

  28. Click the button

    Using a Field as a Class Type

  29. Close the form and return to your programming environment
  30. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  31. In the list of projects templates of the Create a New Project dialog box, click Windows Forms App (.NET Framework)
  32. Create Next
  33. Change the project Name to Chemistry02
  34. Click Create
  35. Design the form as follows:

    Values Conversion - Metric System

    Control (Name) Text
    Label   Symbol:
    TextBox txtSymbol
    Label   Element Name:
    TextBox txtElementName
    Label   Atomic Number:
    TextBox txtAtomicNumber
    Label   Atomic Weight:
    TextBox txtAtomicWeight
  36. On the main menu, click Project -> Add Class...
  37. Change the file name to Element
  38. Click Add
  39. Right-click in the Code Editor and click Remove and Sort Usings
  40. Change the class as follows:
    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;
            }
        }
    }
  41. In the Solution Explorer, right-click Form1.cs and click View Code

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 LearningPractical Learning: Returning an Object

  1. To create and call a function that takes an object as parameter, change the document as follows:
    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();
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Overloading a Constructor

  3. Close the form and return to your programming environment

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 LearningPractical Learning: Returning an Object

  1. To create and call a function that returns an object, change the document as follows:
    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;
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Overloading a Constructor

  3. Close the form and return to your programming environment

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 LearningPractical Learning: Introducing the Returned Object

  1. On the main menu, click File -> New -> Project...
  2. In the Create a New Project dialog box, under Recent Projects Templates, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the name of the project to ElectricityDistribution1
  5. Click Create
  6. Design the form as follows:

    Using the Returned Object of a Method

    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  
  7. On the main menu, click Project -> Add Class...
  8. Set the name as BillPreparation and click Add
  9. Right-click in the Code Editor and click Remove and Sort Usings

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 LearningPractical Learning: Using the Returned Object of a Method

  1. Type code as follows:
    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;
            }
        }
    }
  2. In the Solution Edplorer, right-click Form1.cs and click Rename
  3. Type BillProcessing (to get BillProcessing.cs) and press Enter
  4. Read the message box and click Yes
  5. In the Solution Explorer, right-click BillProcessing.cs and click View Designer
  6. On the form, double-click the Show Meter Details button
  7. Right-click in the Code Editor and click Remove and Sort Usings
  8. Implement the event as follows:
    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();
            }
        }
    }
  9. To execute, on the main menu, click Debug -> Start Without Debugging:

    Using the Returned Object of a Method

  10. Type some values as follows:
    Meter #: FGL-6048
    Make:    Thiesen Power
    Model;   KV-2604

    Using the Returned Object of a Method

  11. Click the Show Meter Details button:

    Using the Returned Object of a Method

  12. Close the form and return to Microsoft Visual Studio
  13. Notice that the Meter class we created contains a simple method that produces a string. Consider another class in the same project.
    Create another class in the document as follows:
    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;
            }
        }
    }
  14. Notice that this new CounterReading class contains a method that returns an object of the type of the other class. You can call such a method to get a reference to the other class. That reference, used as an object, can be used as a valid object gotten from the first class. For example of doing this, click the BillPreparation.cs tab and change the event as follows:
    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();
            }
        }
    }
  15. To execute, on the main menu, click Debug -> Start Without Debugging
  16. Type some values as follows:
    Meter #: WEJ-9284
    Make:    Pepperus Worldwide
    Model;   i2024
  17. Click the Show Meter Details button:

    Using the Returned Object of a Method

  18. Close the form and return to Microsoft Visual Studio
  19. To consider one more class, click the BillPreparation.cs tab and add a new class as follows:
    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;
            }
        }
    }
  20. Click the BillPreparation.cs tab and change the event as follows:
    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();
            }
        }
    }
  21. To execute, on the main menu, click Debug -> Start Without Debugging
  22. Type some values as follows:
    Meter #: KBV-9728
    Make:    Frellatta International
    Model;   G2806T
  23. Click the Show Meter Details button:

    Node Editor

  24. Close the form and return to Microsoft Visual Studio
  25. Once again, the new class contains a method that returns an object of a class. We saw that, to use the return object of a method, you can first declare a variable and then assign the method call to it. That type of variable may be necessary only if you are planning to call the method more than once.

    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;
            }
        }
    }
  26. For examples of calling objects's methods directly where they are needed, click the BillProcessing.cs [Design] and change the document as follows:
    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)
            {
            }
        }
    }
  27. To execute, press Ctrl + F5

    Node Editor

  28. Close the form and return to your programming environment

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);
    }
}

ApplicationPractical Learning: Ending the Lesson


Previous Copyright © 2001-2021, C# Key Next