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: Introducing Constructors with No Bodies

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle list, click Empty Project (.NET Framework) and set the project Name to Geometry02
  4. Click OK
  5. In the Solution Explorer, right-click Geometry02 -> Add -> New Item...
  6. In the left list, under Visual C#, click Code
  7. In the middle list, click Code File
  8. Change the name to EquilateralTriangle
  9. Press Enter
  10. Type the code as follows:
    public 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;
        }
    }
  11. In the Solution Explorer, right-click Geometry02 -> Add -> New Item...
  12. In the middle list, make sure Code File is selected.
    Set the name as Geometry
  13. Click Add
  14. Change the code as follows:
    public class Geometry
    {
        static void Main()
        {
            double side = 224.863;
            EquilateralTriangle et = new EquilateralTriangle();
    
            et = new EquilateralTriangle(side);
    
            System.Console.WriteLine("Geometry - Equilateral Triangle");
            System.Console.WriteLine("---------------------------------");
            System.Console.Write("Side: ");
            System.Console.WriteLine(side);
            System.Console.Write("Perimeter: ");
            System.Console.WriteLine(et.CalculatePerimeter());
            System.Console.WriteLine("==================================");
    
            return 0;
        }
    }
  15. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging:
    Geometry - Equilateral Triangle
    ---------------------------------
    Side: 224.863
    Perimeter: 674.589
    ==================================
    Press any key to continue . . .
  16. Press Enter to close the window and return to your programming environment
  17. Access the EquilateralTriangle.cs file and change the constructors as follows:
    public 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;
        }
    }
  18. To execute the project, on the main menu, click Debug -> Start Without Debugging
  19. Press Enter to close the window and return to your programming environment
  20. Change the EquilateralTriangle class as follows:
    public class EquilateralTriangle
    {
        private double s;
        const double NumberOfSides = 3;
    
        public EquilateralTriangle(double side = 0) => s = side;
    
        public double CalculatePerimeter() => s * NumberOfSides;
    }
  21. To execute the project, on the main menu, click Debug -> Start Without Debugging
  22. Press Enter to close the window 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 whose value can only be read outside the class, precede its data type, during declaration, with the readonly keyword.

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. Because you can initialize a read-only field in a constructor, if you have different constructors, you can also have different values for a 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;
    }
}

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. In the Solution Explorer, right-click Geometry02 -> Add -> New Item...
  2. In the middle list, make sure Code File is selected.
    Change the name to Circle
  3. Press Enter
  4. Type the code as follows:
    public class Circle
    {
        public readonly double PI;
    
        public double Radius;
    
        public Circle()
        {
            Radius = 0.00;
        }
    
        public double CalculateDiameter()
        {
            return Radius * 2.00;
        }
    }
  5. You can initialize a read-only field when declaring it. For an example, change the code as follows:
    public 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;
        }
    }
  6. Access the Geometry.cs file and change the code as follows:
    public class Geometry
    {
        static void Main()
        {
            Circle round = new Circle();
    
            round.Radius = 224.863;
    
            System.Console.WriteLine("Geometry - Circle");
            System.Console.WriteLine("----------------------------");
            System.Console.Write("Radius: ");
            System.Console.WriteLine(round.Radius);
            System.Console.Write("Diameter: ");
            System.Console.WriteLine(round.CalculateDiameter());
            System.Console.Write("Area: ");
            System.Console.WriteLine(round.CalculateArea());
            System.Console.WriteLine("=============================");
    
            return 0;
        }
    }
  7. Execute the application to see the result:
    Geometry - Circle
    ----------------------------
    Radius: 224.863
    Diameter: 449.726
    Area: 158768.97793466
    =============================
    Press any key to continue . . .
  8. Press Enter to close the window and return to your programming environment
  9. You can initialize a read-only field in the (a) constructor of its class. For an example, access the Circle.cs file and change its code as follows:
    public class Circle
    {
        public readonly double PI;
    
        public double Radius;
    
        public Circle()
        {
            PI = 3.14;
            Radius = 0.00;
        }
    
        public double CalculateDiameter()
        {
            return Radius * 2;
        }
    
        public double CalculateArea()
        {
            return Radius * Radius * PI;
        }
    }
  10. Execute the application to see the result
  11. Press Enter to close the window and return to your programming environment
  12. 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:
    public 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;
        }
    
        public double CalculateArea()
        {
            return Radius * Radius * PI;
        }
    }
  13. Access the Geometry.csfile and change it as follows:
    public class Geometry
    {
        static void Main()
        {
            double rad = 224.863;
            Circle round = new Circle();
    
            System.Console.WriteLine("Geometry - Circle");
            System.Console.WriteLine("----------------------------");
            System.Console.Write("PI: ");
            System.Console.WriteLine(round.PI);
            System.Console.Write("Radius: ");
            System.Console.WriteLine(round.Radius);
            System.Console.Write("Diameter: ");
            System.Console.WriteLine(round.CalculateDiameter());
            System.Console.Write("Area: ");
            System.Console.WriteLine(round.CalculateArea());
            System.Console.WriteLine("=============================");
    
            round = new Circle(rad);
    
            System.Console.WriteLine("Geometry - Circle");
            System.Console.WriteLine("----------------------------");
            System.Console.Write("PI: ");
            System.Console.WriteLine(round.PI);
            System.Console.Write("Radius: ");
            System.Console.WriteLine(round.Radius);
            System.Console.Write("Diameter: ");
            System.Console.WriteLine(round.CalculateDiameter());
            System.Console.Write("Area: ");
            System.Console.WriteLine(round.CalculateArea());
            System.Console.WriteLine("=============================");
    
            return 0;
        }
    }
  14. To execute the project, on the main menu, click Debug -> Start Without Debugging
    Geometry - Circle
    ----------------------------
    PI: 3.14
    Radius: 0
    Diameter: 0
    Area: 0
    =============================
    Geometry - Circle
    ----------------------------
    PI: 3.14159
    Radius: 224.863
    Diameter: 449.726
    Area: 158849.373691003
    =============================
    Press any key to continue . . .
  15. Press Enter to close the window 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:

public class Employee
{
    public string FirstName;
    public string LastName;
    public double HourlySalary;
}

public class TimeSheet
{
    Employee staff;
}

You can initialize the variable directly where it is declared. Here is an example:

public class Employee
{
    public string FirstName;
    public string LastName;
    public double HourlySalary;
}

public class TimeSheet
{
    Employee staff = new Employee();
}

Or you can create/use a constructor to initialize it. Here is an example:

public class Employee
{
    public string FirstName;
    public string LastName;
    public double HourlySalary;
}

public class TimeSheet
{
    Employee staff = new Employee();
}

To access a member of the class of the field in the same class where the variable is declared, type the name of the field, a period, and the desired member. Here are examples:

public class Employee
{
    public string FirstName;
    public string LastName;
    public double HourlySalary;
}

public class TimeSheet
{
    public Employee StaffMember;
    public double Monday;
    public double Tuesday;
    public double Wednesday;
    public double Thursday;
    public double Friday;

    public TimeSheet()
    {
        StaffMember = new Employee();
    }

    public double CalculateTimeWorked() => Monday + Tuesday + Wednesday + Thursday + Friday;
    public double CalculateWeeklySalary()
    {
        return StaffMember.HourlySalary * CalculateTimeWorked();
    }
}

To access a member of the class of the field outside the class where the variable is declared, type the name of the variable, a period, the name of the field, a period, and the desired member. Here are examples:

public class Employee
{
    public string FirstName;
    public string LastName;
    public double HourlySalary;
}

public class TimeSheet
{
    public Employee StaffMember;
    public double Monday;
    public double Tuesday;
    public double Wednesday;
    public double Thursday;
    public double Friday;

    public TimeSheet()
    {
        StaffMember = new Employee();
    }

    public double CalculateTimeWorked() => Monday + Tuesday + Wednesday + Thursday + Friday;
    public double CalculateWeeklySalary() => StaffMember.HourlySalary * CalculateTimeWorked();
}

class EmployeesRecords
{   
    static void Main()
    {
        TimeSheet ts = new TimeSheet();
        Employee empl = new Employee();

        empl.FirstName = "Christine";
        empl.LastName = "Law";
        empl.HourlySalary = 22.27;

        ts.StaffMember = empl;

        ts.Monday = 8.00;
        ts.Tuesday = 9.50;
        ts.Wednesday = 6.00;
        ts.Thursday = 9.00;
        ts.Friday = 7.50;

        System.Console.WriteLine("Employee Payroll");
        System.Console.WriteLine("============================");
        System.Console.Write("Employee Name: ");
        System.Console.Write(ts.StaffMember.FirstName);
        System.Console.Write(" ");
        System.Console.WriteLine(ts.StaffMember.LastName);
        System.Console.Write("Hourly Salary: ");
        System.Console.WriteLine(ts.StaffMember.HourlySalary);
        System.Console.WriteLine("---------------------------");
        System.Console.WriteLine("Time Worked");
        System.Console.Write("Monday: ");
        System.Console.WriteLine(ts.Monday);
        System.Console.Write("Tuesday: ");
        System.Console.WriteLine(ts.Tuesday);
        System.Console.Write("Wednesday: ");
        System.Console.WriteLine(ts.Wednesday);
        System.Console.Write("Thursday: ");
        System.Console.WriteLine(ts.Thursday);
        System.Console.Write("Friday: ");
        System.Console.WriteLine(ts.Friday);
        System.Console.Write("Time Worked: ");
        System.Console.WriteLine(ts.CalculateTimeWorked());
        System.Console.Write("Weekly Salary: ");
        System.Console.WriteLine(ts.CalculateWeeklySalary());
    }
}

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, a 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. In the Solution Explorer, right-click Geometry02 -> Add -> New Item...
  2. In the middle frame, make sure Code File is selected.
    Change the code to Rectangle
  3. Click Add
  4. Type the code as follows:
    public class Rectangle
    {
        public double Width;
        public double Height;
    }
  5. In the Solution Explorer, right-click Geometry02 -> Add -> New Item...
  6. In the middle list, make sure Code File is selected.
    Change the name to Box
  7. Press Enter
  8. Type the code as follows:
    public class Box
    {
        public double Depth;
        public Rectangle Face;
    }
  9. Access the Geometry.cs file and change the code as follows:
    public class Geometry
    {
        public static int Main()
        {
            double width = 279.739;
            double height = 216.426;
            double depth = 97.268;
    
            Box rectangular = new Box();
    
            rectangular.Face = new Rectangle();
    
            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;
    
            System.Console.WriteLine("Geometry - Rectangular Box");
            System.Console.WriteLine("----------------------------");
            System.Console.Write("Width: ");
            System.Console.WriteLine(width);
            System.Console.Write("Height: ");
            System.Console.WriteLine(height);
            System.Console.Write("Depth: ");
            System.Console.WriteLine(depth);
            System.Console.Write("Front / Back: ");
            System.Console.WriteLine(frontBackPerimeter);
            System.Console.Write("Left / Right: ");
            System.Console.WriteLine(leftRightPerimeter);
            System.Console.Write("Top / Bottom: ");
            System.Console.WriteLine(topBottomPerimeter);
            System.Console.WriteLine("=============================");
    
            return 0;
        }
    }
  10. Execute the application to see the result:
    Geometry - Rectangular Box
    ----------------------------
    Width: 279.739
    Height: 216.426
    Depth: 97.268
    Front / Back: 992.33
    Left / Right: 627.388
    Top / Bottom: 754.014
    =============================
    Press any key to continue . . .
  11. Press Enter to close the window and return to your programming environment

A Class Type as Parameter

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. As a result, an object of a class can be passed as argument. Here is an example:

public class StoreItem
{
    public int ItemNumber;
    public string ItemName;
    public double UnitPrice;

    public StoreItem(int nbr, string name, double price)
    {
        ItemNumber = nbr;
        ItemName   = name;
        UnitPrice  = price;
    }
}

class Inventory
{
    public double TaxRate;

    public double CalculateDiscountAmount(StoreItem item, double discRate = 50.00)
    {
        return item.UnitPrice * discRate / 100.00;
    }

    public double CalculateTaxAmount(double amount)
    {
        return amount * TaxRate / 100;
    }
    public double CalculatePriceAfterDiscount(StoreItem item, double discRate = 50.00)
    {
        double discount = CalculateDiscountAmount(item, discRate);
        
        return item.UnitPrice - discount;
    }
}

class DepartmentStore
{
    static void Main()
    {
        StoreItem si = new StoreItem(852924, "Striped Blue Dress", 98.65);

        Inventory inv = new Inventory();
        inv.TaxRate = 7.75;

        double discount = inv.CalculateDiscountAmount(si, 25);

        System.Console.WriteLine("Fun Department Store - Inventory");
        System.Console.Write("Item Number: ");
        System.Console.WriteLine(si.ItemNumber);
        System.Console.Write("Item Name: ");
        System.Console.WriteLine(si.ItemName);
        System.Console.Write("Original Price: ");
        System.Console.WriteLine(si.UnitPrice);
        System.Console.Write("Discount Amount: ");
        System.Console.WriteLine(discount);
        System.Console.Write("Tax Rate: ");
        System.Console.WriteLine(inv.TaxRate);
        System.Console.Write("Tax Amount: ");
        System.Console.WriteLine(inv.CalculateTaxAmount(si.UnitPrice));
        System.Console.Write("Price After Discount: ");
        System.Console.WriteLine(inv.CalculatePriceAfterDiscount(si, 25));
    }
}

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.

Returning an Object

Introduction

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(10M);

		. . . 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 the variable. 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 the variable. 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();
    }
}

Having Many Methods that Return the Same Type of Object

Imagine you have a method that returns an object. Here is an example:

public class Operation
{
    public double Number1;
    public double Number2;
    public string  Operator;

    public Operation(double nbr1, string oper, double nbr2)
    {
        Number1 = nbr1;
        Number2 = nbr2;
        Operator = oper;
    }
}

public class Algebra
{
    public double First;
    public double Second;
    public string  Performance;

    public Operation Calculate()
    {
        Operation op = new Operation(First, Performance, Second);

        return op;
    }

    public Operation Add()
    {
        return Calculate();
    }
}

You can also have another or more methods that perform the same type of operation and/or return the same type of object. You don't need to declare a variable to call the first method. Here are examples:

public class Operation
{
    public double Number1;
    public double Number2;
    public string  Operator;

    public Operation(double nbr1, string oper, double nbr2)
    {
        Number1 = nbr1;
        Number2 = nbr2;
        Operator = oper;
    }
}

public class Algebra
{
    public double First;
    public double Second;
    public string  Performance;

    public Operation Calculate()
    {
        Operation op = new Operation(First, Performance, Second);

        return op;
    }

    public Operation Add()
    {
        return Calculate();
    }

    public Operation Subtract()
    {
        return Calculate();
    }

    public Operation Multiply()
    {
        return Calculate();
    }
}

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.

Using the Returned Object of a Method

Consider the following class created in a file named BillPreparation.cs:

// Eletricity Distribution Company
public class Meter
{
    public string MeterNumber { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }

    
    public string Describe()
    {
        string strMMM = Make + " " + Model + " (" + MeterNumber + ")";

        return strMMM;
    }
}

Notice that this class contains a simple method that produces a string. Consider another class in the same project:

// Eletricity Distribution Company
public class Meter
{
    public string MeterNumber { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }

    public string Describe()
    {
        return Make + " " + Model + " (" + MeterNumber + ")";
    }
}

public class CounterReading
{
    private Meter mtr;
    public int TotalUse { get; set; }

    public CounterReading()
    {
        mtr = new Meter();
    }

    public Meter Read()
    {
        return mtr;
    }
}

Notice that this new CounterReading class contains a method that returns an object of the type of the other class. Consider one more class as follows:

// Eletricity Distribution Company
public class Meter
{
    public string MeterNumber { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }

    public string Describe()
    {
        return Make + " " + Model + " (" + MeterNumber + ")";
    }
}

public class CounterReading
{
    private Meter mtr;
    public int TotalUse { get; set; }

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

Once again, this 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 that variable. Here is an example:

// Eletricity Distribution Company
public class Meter
{
    public string MeterNumber { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }

    public string Describe()
    {
        return Make + " " + Model + " (" + MeterNumber + ")";
    }
}

public class CounterReading
{
    private Meter mtr;

    public Meter Read()
    {
        return mtr;
    }
}

public class Calculations
{
    public CounterReading Useage;

    public Calculations()
    {
        Useage = new CounterReading();
    }

    public CounterReading Prepare()
    {
        return Useage;
    }
}

public class ElectriBill
{
    private Calculations values;

    public ElectriBill()
    {
        values = new Calculations();
    }

    public void Calculate()
    {
        CounterReading cr = new CounterReading();
        Calculations calc = new Calculations();

        cr = calc.Prepare();
    }
}

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

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

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

class EmployeesRecords
{   
    static void Main()
    {
        double width = 227.816, height = 184.307, area = 0.00;

        Triangle tri = new Triangle(width, height);
        area = tri.CalculateArea();

        System.Console.WriteLine("Triangle Characteristics");
        System.Console.WriteLine("---------------------------");
        System.Console.Write("Width: ");
        System.Console.WriteLine(width);
        System.Console.Write("Height: ");
        System.Console.WriteLine(height);
        System.Console.Write("Area: ");
        System.Console.WriteLine(area);
        System.Console.WriteLine("============================");
    }
}

This would produce:

Triangle Characteristics
---------------------------
Width: 227.816
Height: 184.307
Area: 20994.041756
============================
Press any key to continue . . .

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:

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

class EmployeesRecords
{   
    static void Main()
    {
        double width = 227.816, height = 184.307, area = 0.00;

        area = new Triangle(width, height).CalculateArea();

        System.Console.WriteLine("Triangle Characteristics");
        System.Console.WriteLine("---------------------------");
        System.Console.Write("Width: ");
        System.Console.WriteLine(width);
        System.Console.Write("Height: ");
        System.Console.WriteLine(height);
        System.Console.Write("Area: ");
        System.Console.WriteLine(area);
        System.Console.WriteLine("============================");   
    }
}

Accessing an Object by its New Reference

In most cases, to create an object, we have 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();

You can also access a member of the class from that reference. 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;
}

class EmployeesRecords
{   
    static void Main()
    {
        double width = 227.816, height = 184.307;

        System.Console.WriteLine("Triangle Characteristics");
        System.Console.WriteLine("---------------------------");
        System.Console.Write("Width: ");
        System.Console.WriteLine(width);
        System.Console.Write("Height: ");
        System.Console.WriteLine(height);
        System.Console.Write("Area: ");
        System.Console.WriteLine(new Triangle(width, height).CalculateArea());
        System.Console.WriteLine("============================");
    }
}

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-2019, FunctionX Next