Inheritance With the Base Class

Inheriting the Base Object

After creating a derived class, to let you access the parent class, the C# language provides a keyword named base that gives a child class access to public and protected members of its parent class.

Practical LearningPractical Learning: Accessing the Base Object from a Child Class

  1. Start Microsoft Visual Studio. Create a new Console App named Volumetrics3 that uses .NET 8.0 (Long-Term Support)
  2. To create a new folder, in the Solution Explorer, right-click Volumetrics3 -> Add -> New Folder
  3. Type Models as the name of the folder
  4. In the Solution Explorer, right-click Models -> Add -> Class...
  5. In the middle list of the Add New Item dialog box, make sure Class is selected.
    Change the Name of the file to Trapezoid
  6. Click Add
  7. Change the document as follows:

    Square

    namespace Volumetrics3.Models
    {
        internal class Trapezoid
        {
            public double TopBase    { get; set; }
            public double BottomBase { get; set; }
            public double Height     { get; set; }
    
            public double Area
            {
                get
                {
                    return Height * (TopBase + BottomBase) / 2.00;
                }
            }
        }
    }
  8. In the Solution Explorer, right-click Models -> Add -> Class...
  9. In the middle list of the Add New Item dialog box, make sure Code File is selected.
    Change the name of the file to TrapezoidalPrism
  10. Click Add
  11. Change the class as follows:

    Square

    namespace Volumetrics3.Models
    {
        internal class TrapezoidalPrism : Trapezoid
        {
            private double len;
    
            public double Length
            {
                get
                {
                    return len;
                }
    
                set
                {
                    len = value;
                }
            }
    
            public double BaseArea
            {
                get
                {
                    // "base" refers to a parent's property
                    return base.Area;
                }
            }
    
            public double TopArea
            {
                get
                {
                    // "base" TopBase refers to a parent's property
                    return base.TopBase * Length;
                }
            }
    
            public double BottomArea
            {
                get
                {
                    // "base" BottomBase refers to a parent's property
                    return base.BottomBase * Length;
                }
            }
    
            public double Volume
            {
                get
                {
                    // "base" Area refers to a parent's property
                    return base.Area * Length;
                }
    	}
        }
    }
  12. In the Solution Explorer, right-click Program.cs -> Rename
  13. Type figure Geometry (to get Geometry.cs) and press Enter
  14. Read the content of the message box and click Yes
  15. Click the Geometry.cs tab to access the document and change it as follows:
    using static System.Console;
    using Volumetrics3.Models;
    
    double top    = 0.00;
    double bottom = 0.00;
    double height = 0.00;
    double length = 0.00;
    TrapezoidalPrism tp = new TrapezoidalPrism();
    
    WriteLine("================================================");
    WriteLine("Geometry - Trapezoidal Prism");
    WriteLine("================================================");
    WriteLine("Enter the values to process a trapezoidal prism");
    WriteLine("------------------------------------------------");
    
    try
    {
        Write("Top Base:    ");
        top = double.Parse(ReadLine()!);
    }
    catch (FormatException fe)
    {
        WriteLine("There was an error for the value of the top base." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Bottom Base: ");
        bottom = double.Parse(ReadLine()!);
    }
    catch (FormatException fe)
    {
        WriteLine("There was an error for the value of the bottom base." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Height:      ");
        height = double.Parse(ReadLine()!);
    }
    catch (FormatException fe)
    {
        WriteLine("There was an error for the value of the height." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Length:      ");
        length = double.Parse(ReadLine()!);
    }
    catch (FormatException fe)
    {
        WriteLine("There was an error for the value of the length." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    tp.TopBase = top;
    tp.BottomBase = bottom;
    tp.Height = height;
    tp.Length = length;
    
    WriteLine("================================================");
    WriteLine("Geometry - Trapezoidal Prism");
    WriteLine("================================================");
    WriteLine("Dimensions");
    WriteLine("------------------------------------------------");
    WriteLine("Top Base:    {0}", tp.TopBase);
    WriteLine("Bottom Base: {0}", tp.BottomBase);
    WriteLine("Height:      {0}", tp.Height);
    WriteLine("Length:      {0}", tp.Length);
    WriteLine("================================================");
    WriteLine("Areas");
    WriteLine("------------------------------------------------");
    WriteLine("Base Area:   {0}", tp.BaseArea);
    WriteLine("Top Area:    {0}", tp.TopArea);
    WriteLine("Bottom Area: {0}", tp.BottomArea);
    WriteLine("------------------------------------------------");
    WriteLine("Volume:      {0}", tp.Volume);
    WriteLine("================================================");
  16. To execute the project, on the main menu, click Debug -> Start Without Debugging:
  17. When requested, type the value of the Top Base as 137.96 and press Enter
  18. For the Bottom Base, type 209.73 and press Enter
  19. For the Height, type 87.59 and press Enter
  20. For the Length, type 142.46 and press Enter:
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Enter the values to process a trapezoidal prism
    ------------------------------------------------
    Top Base:    137.96
    Bottom Base: 209.73
    Height:      87.59
    Length:      142.46
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Dimensions
    ------------------------------------------------
    Top Base:    137.96
    Bottom Base: 209.73
    Height:      87.59
    Length:      142.46
    ================================================
    Areas
    ------------------------------------------------
    Base Area:   15227.083550000001
    Top Area:    19653.781600000002
    Bottom Area: 29878.1358
    ------------------------------------------------
    Volume:      2169250.3225330003
    ================================================
    
    Press any key to close this window . . .
  21. Return to your programming environment, press Enter

Inheriting the Base Constructors

If a parent class has a constructor, you can call that constructor in the child class. The constructor is accessed using the base keyword preceded by a colon. The keyword is accessed as when calling a method but after the parentheses of a constructor in the child class. That is, it must use parentheses. The primary formula to follow is:

class class-name : parent-name
{
    access-level class-name(parameter(s)) : base(parameter(s))
}

To call the base() constructor in a constructor of a child class, there are a few rules you must follow:

To use the base() constructor, the constructor on it is applied in the child class and must use more than the number of parameters and same type(s) of parameter(s) as the constructor of the parent class.

To call a constructor of the parent class from the derived class, if you are calling a constructor that doesn't use any parameter, leave the parentheses empty. Here is an example:

internal class Circle
{
    private double _radius;

    public Circle()
    {
        _radius = 0.00;
    }
}

internal class Cone : Circle
{
    private double _height;

    public Cone() : base()
    {
        _height = 0.00;
    }
}

If you are calling a constructor that uses one parameter, in the parentheses of base(), type the name of the parameter. Here is an example:

using System;

internal class Circle
{
    private double _radius;

    public Circle(double rad)
    {
        _radius = rad;
    }
}

internal class Cone : Circle
{
    private double _height;

    public Cone(double rad, double hgt) : base(rad)
    {
        _height = hgt;
    }
}

If the constructor of the parent class uses more than one parameter, in the parentheses of base, enter the names of the parameters of the child contructor that is calling it. Here is an example:

internal class Person
{
    public string? FirstName { get; set; }
    public string ?LastName  { get; set; }

    public Person(string fName, string lName)
    {
        FirstName = fName;
        LastName  = lName;
    }
}

internal class Employee : Person
{
    public Employee(string fName, string lName) : base(fName, lName)
    {
    }
}

To make your code easy to read, you can call the base() constructor on the next line. Here is an example:

internal class Person
{
    public string? FirstName { get; set; }
    public string ?LastName  { get; set; }

    public Person(string fName, string lName)
    {
        FirstName = fName;
        LastName  = lName;
    }
}

internal class Employee : Person
{
    public Employee(string fName, string lName)
        : base(fName, lName)
    {
    }
}

If the child construtor uses more parameters than the parent constructor, you can initialize the extra parameter(s) in the body of the (child) constructor. Here is an example:

internal class Person
{
    public string? FirstName { get; set; }
    public string ?LastName  { get; set; }

    public Person(string fName, string lName)
    {
        FirstName = fName;
        LastName  = lName;
    }
}

internal class Employee : Person
{
    public Employee(string fName, string lName, double salary)
        : base(fName, lName)
    {
        HourlySalary = salary;
    }

    public double HourlySalary { get; set; }
}

Practical LearningPractical Learning: Inheriting a Base Constructor

  1. Click the Trapezoid.cs tab to access the file
  2. Add a constructor to the class as follows:
    namespace Volumetrics3.Models
    {
        internal class Trapezoid
        {
            public double TopBase    { get; set; }
            public double BottomBase { get; set; }
            public double Height     { get; set; }
    
            public Trapezoid(double top, double bottom, double height)
            {
                TopBase    = top;
                BottomBase = bottom;
                Height     = height;
            }
    
            public double Area
            {
                get
                {
                    return Height * (TopBase + BottomBase) / 2.00;
                }
    	}
        }
    }
  3. Click the TrapezoidalPrism.cs tab to access its file
  4. Create a constructor in the class as follows:
    namespace Volumetrics3.Models
    {
        internal class TrapezoidalPrism: Trapezoid
        {
            private double len;
    
            public TrapezoidalPrism(double top, double bottom, double height, double length)
                    : base(top, bottom, height)
            {
                Length = length;
            }
    
            . . . No Change
        }
    }
  5. Click the Geometry.cs tab to access the file
  6. Change the code as follows:
    using static System.Console;
    using Volumetrics3.Models;
    
    WriteLine("================================================");
    WriteLine("Geometry - Trapezoidal Prism");
    WriteLine("================================================");
    WriteLine("Enter the values to process a trapezoidal prism");
    WriteLine("------------------------------------------------");
    
    double top    = 0.00;
    double bottom = 0.00;
    double height = 0.00;
    double length = 0.00;
    
    try
    {
        Write("Top Base:    ");
        top = double.Parse(ReadLine()!);
    }
    catch (Exception exc) when (exc is FormatException fe)
    {
        WriteLine("There was an error for the value of the top base." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Bottom Base: ");
        bottom = double.Parse(ReadLine()!);
    }
    catch (Exception exc) when (exc is FormatException fe)
    {
        WriteLine("There was an error for the value of the bottom base." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Height:      ");
        height = double.Parse(ReadLine()!);
    }
    catch (Exception exc) when (exc is FormatException fe)
    {
        WriteLine("There was an error for the value of the height." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Length:      ");
        length = double.Parse(ReadLine()!);
    }
    catch (Exception exc) when (exc is FormatException fe)
    {
        WriteLine("There was an error for the value of the length." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    TrapezoidalPrism tp = new TrapezoidalPrism(top, bottom, height, length);
    
    WriteLine("================================================");
    WriteLine("Geometry - Trapezoidal Prism");
    WriteLine("================================================");
    WriteLine("Dimensions");
    WriteLine("------------------------------------------------");
    WriteLine("Top Base:    {0}", tp.TopBase);
    WriteLine("Bottom Base: {0}", tp.BottomBase);
    WriteLine("Height:      {0}", tp.Height);
    WriteLine("Length:      {0}", tp.Length);
    WriteLine("================================================");
    WriteLine("Areas");
    WriteLine("------------------------------------------------");
    WriteLine("Base Area:   {0}", tp.BaseArea);
    WriteLine("Top Area:    {0}", tp.TopArea);
    WriteLine("Bottom Area: {0}", tp.BottomArea);
    WriteLine("------------------------------------------------");
    WriteLine("Volume:      {0}", tp.Volume);
    WriteLine("================================================");
  7. To execute the application and test the form, press Ctrl + F5
  8. For the Top Base, type 588.97 and press Enter
  9. For the Bottom Base, type 836.84 and press Enter
  10. For the Height, type 1079.41 and press Enter
  11. For the Length, type 1326.73 and press Enter:
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Enter the values to process a trapezoidal prism
    ------------------------------------------------
    Top Base:    588.97
    Bottom Base: 836.84
    Height:      1079.41
    Length:      1326.73
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Dimensions
    ------------------------------------------------
    Top Base:    588.97
    Bottom Base: 836.84
    Height:      1079.41
    Length:      1326.73
    ================================================
    Areas
    ------------------------------------------------
    Base Area:   769516.78605
    Top Area:    781404.1681
    Bottom Area: 1110260.7332000001
    ------------------------------------------------
    Volume:      1020941005.5561165
    ================================================
    
    Press any key to close this window . . .
  12. Return to your programming environment, press A

Inheritance With this Class

Inheritance With this Object

We already know that every non-static class is equipped with an object named this. If you derive a class from a parent class, the child class has direct access to all public, internal, and protected members of the parent class. As an alternative to indicate that you are accessing a local member or a member of the parent class, in the child class, you can start the name of the member with this..

Practical LearningPractical Learning: Inheriting this Parent

  1. Access the TrapezoidalPrism.cs file and change its class as follows:
    namespace Volumetrics3.Models
    {
        internal class TrapezoidalPrism: Trapezoid
        {
            private double len;
    
            public TrapezoidalPrism(double top, double bottom, double height, double length)
                    : base(top, bottom, height)
            {
                // "this" refers to a local property
                this.Length = length;
            }
    
            public double Length
            {
                get
                {
                    // "this" refers to a local field
                    return this.len;
                }
    
                set
                {
                    // "this" refers to a local field
                    this.len = value;
                }
            }
    
            public double BaseArea
            {
                get
                {
                    // "base" refers to a parent
                    return base.Area;
                }
            }
    
            public double TopArea
            {
                get
                {
                    // "this" TopBase refers to a parent's property
                    // "this" refers to a local property
                    return this.TopBase * this.Length;
                }
            }
    
            public double BottomArea
            {
                get
                {
                    // "this" BottomBase refers to a parent's property
                    // "this" refers to a local property
                    return this.BottomBase * this.Length;
                }
            }
    
            public double Volume
            {
                get
                {
                    // "base" Area refers to a parent's property
                    // "this" refers to a local property
                    return base.Area * this.Length;
    	    }
            }
        }
    }
  2. To execute the application and test the form, press Ctrl + F5
  3. For the Top Base, type 357.93 and press Enter
  4. For the Bottom Base, type 637.77 and press Enter
  5. For the Height, type 2263.79 and press Enter
  6. For the Length, type 975.86 and press Enter:
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Enter the values to process a trapezoidal prism
    ------------------------------------------------
    Top Base:    357.93
    Bottom Base: 637.77
    Height:      2263.79
    Length:      975.86
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Dimensions
    ------------------------------------------------
    Top Base:    357.93
    Bottom Base: 637.77
    Height:      2263.79
    Length:      975.86
    ================================================
    Areas
    ------------------------------------------------
    Base Area:   1127027.8515
    Top Area:    349289.5698
    Bottom Area: 622374.2322
    ------------------------------------------------
    Volume:      1099821399.1647902
    ================================================
    
    Press any key to close this window . . .
  7. To close the window and return to your programming environment
  8. Click the Trapezoid.cs tab to access the file
  9. Change the code of the Area as follows:
    namespace Volumetrics3.Models
    {
        internal class Trapezoid
        {
            public double TopBase { get; set; }
            public double BottomBase { get; set; }
            public double Height { get; set; }
    
            public Trapezoid(double top, double bottom, double height)
            {
                TopBase = top;
                BottomBase = bottom;
                Height = height;
            }
    
            public double Area => Height * (TopBase + BottomBase) / 2.00;
        }
    }
  10. Click the TrapezoidalPrism.cs tab to access its file
  11. Reduce its code as follows:
    namespace Volumetrics3.Models
    {
        internal class TrapezoidalPrism : Trapezoid
        {
            private double len;
    
            public TrapezoidalPrism(double top, double bottom, double height, double length)
                    : base(top, bottom, height)
            { 
                Length = length;
            }
    
            public double Length
            {
               get => len;
                set => len = value;
            }
    
            public double BaseArea
            {
                // "base" refers to a parent's property
                get => base.Area;
            }
    
            public double TopArea
            {
                // "base" TopBase refers to a parent's property
                get => base.TopBase * Length;
            }
    
            public double BottomArea
            {
                // "base" BottomBase refers to a parent's property
                get => base.BottomBase * Length;
            }
    
            public double Volume
            {
                // "base" Area refers to a parent's property
                get => base .Area * Length;
            }
        }
    }
  12. To execute the application to test the code and make sure there is no error, press Ctrl + F5
  13. Close the window and return to your programming environment
  14. Click the TrapezoidalPrism.cs tab to access its file
  15. Reduce the code of the constructor as follows:
    namespace Volumetrics3.Models
    {
        internal class TrapezoidalPrism : Trapezoid
        {
            private double len;
    
            // "this" refers to a local property
            public TrapezoidalPrism(double top, double bottom, double height, double length)
                    : base(top, bottom, height) => this.Length = length;
    
            public double Length
            {
                // "this" refers to a local field
                get => this.len;
    
                // "this" refers to a local field
                set => this.len = value;
            }
    
            public double BaseArea
            {
                // "base" refers to a parent
                get => base.Area;
            }
    
            public double TopArea
            {
                // "this" TopBase refers to a parent's property
                // "this" refers to a local property
                get => this.TopBase * this.Length;
            }
    
            public double BottomArea
            {
                // "this" BottomBase refers to a parent's property
                // "this" refers to a local property
                get => this.BottomBase * this.Length;
            }
    
            public double Volume
            {
                // "base" Area refers to a parent's property
                // "this" refers to a local property
                get => base.Area * this.Length;
    	}
        }
    }
  16. Click the Geometry.cs tab to access the file
  17. Change the document as follows:
    using static System.Console;
    
    TrapezoidalPrism Prepare()
    {
        WriteLine("================================================");
        WriteLine("Geometry - Trapezoidal Prism");
        WriteLine("================================================");
        WriteLine("Enter the values to process a trapezoidal prism");
        WriteLine("------------------------------------------------");
        
        double top    = 0.00;
        double bottom = 0.00;
        double height = 0.00;
        double length = 0.00;
    
        try
        {
            Write("Top Base:    ");
            top = double.Parse(ReadLine()!);
        }
        catch (Exception exc) when (exc is FormatException fe)
        {
            WriteLine("There was an error for the value of the top base." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        try
        {
            Write("Bottom Base: ");
            bottom = double.Parse(ReadLine()!);
        }
        catch (Exception exc) when (exc is FormatException fe)
        {
            WriteLine("There was an error for the value of the bottom base." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        try
        {
            Write("Height:      ");
            height = double.Parse(ReadLine()!);
        }
        catch (Exception exc) when (exc is FormatException fe)
        {
            WriteLine("There was an error for the value of the height." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        try
        {
            Write("Length:      ");
            length = double.Parse(ReadLine()!);
        }
        catch (Exception exc) when (exc is FormatException fe)
        {
            WriteLine("There was an error for the value of the length." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        return new TrapezoidalPrism(top, bottom, height, length);
    }
    
    void Present(TrapezoidalPrism trap)
    {
        WriteLine("================================================");
        WriteLine("Geometry - Trapezoidal Prism");
        WriteLine("================================================");
        WriteLine("Dimensions");
        WriteLine("------------------------------------------------");
        WriteLine("Top Base:    {0}", trap.TopBase);
        WriteLine("Bottom Base: {0}", trap.BottomBase);
        WriteLine("Height:      {0}", trap.Height);
        WriteLine("Length:      {0}", trap.Length);
        WriteLine("================================================");
        WriteLine("Areas");
        WriteLine("------------------------------------------------");
        WriteLine("Base Area:   {0}", trap.BaseArea);
        WriteLine("Top Area:    {0}", trap.TopArea);
        WriteLine("Bottom Area: {0}", trap.BottomArea);
        WriteLine("------------------------------------------------");
        WriteLine("Volume:      {0}", trap.Volume);
        WriteLine("================================================");
    }
    
    TrapezoidalPrism tp = Prepare();
    
    Present(tp);
  18. To execute the application and test the code, press Ctrl + F5
  19. For the Top Base, type 559.78 and press Enter
  20. For the Bottom Base, type 528.96 and press Enter
  21. For the Height, type 1247.33 and press Enter
  22. For the Length, type 838.63 and press Enter:
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Enter the values to process a trapezoidal prism
    ------------------------------------------------
    Top Base:    559.78
    Bottom Base: 528.96
    Height:      1247.33
    Length:      838.63
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Dimensions
    ------------------------------------------------
    Top Base:    559.78
    Bottom Base: 528.96
    Height:      1247.33
    Length:      838.63
    ================================================
    Areas
    ------------------------------------------------
    Base Area:   679009.0321
    Top Area:    469448.3014
    Bottom Area: 443601.7248
    ------------------------------------------------
    Volume:      569437344.5900229
    ================================================
    Press any key to continue . . .
  23. To close the window and return to your programming environment, press Z
  24. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
  25. Make sure C# and Console Application are selected.
    Click Next
  26. Replace the name of the project with Volumetrics4
  27. Click Next
  28. Make sure .NET 8.0 (Long-Term Support) is set in the Framework combo box. Click Create
  29. To create a new folder, in the Solution Explorer, right-click Volumetrics4 -> Add -> New Folder
  30. Type Models as the name of the folder
  31. In the Solution Explorer, right-click the second Models -> Add -> Class...
  32. In the middle list of the Add New Item dialog box, nake sure Class is selected.
    Set the name of the class as Cylinder
  33. Click Add
  34. Change the class as follows:

    Square

    namespace Volumetrics4.Models
    {
        internal class Cylinder
        {
            public double Length { get; set; }
            public double Radius { get; set; }
    
            public double Diameter      => this.Radius * 2.00;
            public double Circumference => this.Diameter * 3.141592653589793238462643;
            public double CrossArea     => this.Radius * this.Radius * 3.141592653589793238462643;
            public double LateralArea   => this.Circumference * this.Length;
            public double CentralVolume => this.CrossArea * this.Length;
        }
    }
  35. In the Solution Explorer, right-click Program.cs -> Rename
  36. Type Geometry (to get Geometry.cs) and press Enter
  37. On the message box, click Yes
  38. Change the document as follows:
    using static System.Console;
    using Volumetrics4.Models;
    
    void Present(Cylinder round)
    {
        WriteLine("================================================");
        WriteLine("Geometry - Cylinder");
        WriteLine("================================================");
        WriteLine("Dimensions");
        WriteLine("------------------------------------------------");
        WriteLine("Radius:         {0}", round.Radius);
        WriteLine("Length:         {0}", round.Length);
        WriteLine("================================================");
        WriteLine("Values");
        WriteLine("------------------------------------------------");
        WriteLine("Diameter:       {0}", round.Diameter);
        WriteLine("Circumference:  {0}", round.Circumference);
        WriteLine("Cross Area:     {0}", round.CrossArea);
        WriteLine("Lateral Area:   {0}", round.LateralArea);
        WriteLine("Central Volume: {0}", round.CentralVolume);
        WriteLine("================================================");
    }
    
    double radius = 0.00;
    double length = 0.00;
    Cylinder body = new Cylinder();
    
    WriteLine("================================================");
    WriteLine("Geometry - Cylinder");
    WriteLine("================================================");
    WriteLine("Enter the values to process a cylinder");
    WriteLine("------------------------------------------------");
    
    try
    {
        Write("Radius:       ");
        radius = double.Parse(ReadLine()!);
    }
    catch (FormatException fe)
    {
        WriteLine("An error was produced when requesting the radius of the base of the cylinder." + Environment.NewLine +
                  "The error to report is: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Length:         ");
        length = double.Parse(ReadLine()!);
    }
    catch (FormatException fe)
    {
        WriteLine("An error was produced when requesting the length of the cylinder." + Environment.NewLine +
                  "The error to report is: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    body.Radius = radius;
    body.Length = length;
    
    Present(body);
  39. To execute the project, on the main menu, click Debug -> Start Without Debugging:
  40. When requested, type the Radius as 79.84 and press Enter
  41. For the Length, type 258.93 and press Enter:
    ================================================
    Geometry - Cylinder
    ================================================
    Enter the values to process a cylinder
    ------------------------------------------------
    Top Base:       79.84
    Length:         258.93
    ================================================
    Geometry - Cylinder
    ================================================
    Dimensions
    ------------------------------------------------
    Radius:         79.84
    Length:         258.93
    ================================================
    Values
    ------------------------------------------------
    Diameter:       159.68
    Circumference:  501.64951492521817
    Cross Area:     20025.84863581471
    Lateral Area:   129892.10889958675
    Central Volume: 5185292.987271503
    ================================================
    
    Press any key to close this window . . .
  42. To close the window and return to your programming environment, press Z
  43. To add a class, on the main menu, click Models -> Add -> Class...
  44. Make sure Class is selected in the middle list. Change the name of the file to Tank
  45. Click Add
  46. Change the document as follows:

    Square

    namespace Volumetrics4.Models
    {
        internal class Tank : Cylinder
        {
            public double Width
            {
                get
                {
                    return this.Diameter;
                }
            }
    
            public double TotalLength
            {
                get
                {
                    return this.Length + this.Radius + this.Radius;
                }
            }
    
            public double TotalArea
            {
                get
                {
                    // Area on one side (half sphere) = Area of Sphere / 2
                    // Areas on both sides = area of a sphere = radius * radius * 4 * PI
                    // Total External Area = lateral area (of the central cylinder) + areas on both sides
                    return this.LateralArea + (this.Radius * this.Radius * 3.141592653589793238462643 * 4.00);
                }
            }
    
            public double TotalVolume
            {
                get
                {
                    // Volume on one side (half sphere) = Volue of Sphere / 2
                    // Volumes on both sides = volume of a sphere = radius * radius * radius * 3.141592653589793238462643 * 4 / 3
                    // Total Volume = central volume + volumes on both sides (which is the volume of a sphere)
                    return this.CentralVolume + (this.Radius * this.Radius * this.Radius * 3.141592653589793238462643 * 4.00 / 3.00);
                }
            }
        }
    }
  47. Click the Geometry.cs tab
  48. Change the document as follows:
    using static System.Console;
    using Volumetrics4;
    
    void Present(Tank vol)
    {
        WriteLine("================================================");
        WriteLine("Geometry - Tank");
        WriteLine("================================================");
        WriteLine("Dimensions");
        WriteLine("------------------------------------------------");
        WriteLine("Radius:         {0}", vol.Radius);
        WriteLine("Length:         {0}", vol.Length);
        WriteLine("================================================");
        WriteLine("Values");
        WriteLine("------------------------------------------------");
        WriteLine("Diameter:       {0}", vol.Diameter);
        WriteLine("Circumference:  {0}", vol.Circumference);
        WriteLine("Cross Area:     {0}", vol.CrossArea);
        WriteLine("Lateral Area:   {0}", vol.LateralArea);
        WriteLine("Central Volume: {0}", vol.CentralVolume);
        WriteLine("Width.Text:     {0}", vol.Width);
        WriteLine("Lateral Length: {0}", vol.TotalLength);
        WriteLine("Total Area:     {0}", vol.TotalArea);
        WriteLine("Total Volume:   {0}", vol.TotalVolume);
        WriteLine("================================================");
    }
    
    Tank whole = new Tank();
    double radius = 0.00, length = 0.00;
    
    WriteLine("================================================");
    WriteLine("Geometry - Cylinder");
    WriteLine("================================================");
    WriteLine("Enter the values to process a cylinder");
    WriteLine("------------------------------------------------");
    
    try
    {
        Write("Radius:       ");
        radius = double.Parse(ReadLine()!);
    }
    catch (Exception ex) when (ex is FormatException fe)
    {
        WriteLine("An error was produced when requesting the radius of the base of the cylinder." + Environment.NewLine +
                  "The error to report is: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Length:         ");
        length = double.Parse(ReadLine()!);
    }
    catch (Exception ex) when (ex is FormatException fe)
    {
        WriteLine("An error was produced when requesting the length of the cylinder." + Environment.NewLine +
                  "The error to report is: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    whole.Radius = radius;
    whole.Length = length;
    
    Present(whole);
  49. To execute the project, on the main menu, click Debug -> Start Without Debugging:
  50. For the Radius, type 279.84 and press Enter
  51. For the Length, type 858.93 and press Enter:
    ================================================
    Geometry - Cylinder
    ================================================
    Enter the values to process a cylinder
    ------------------------------------------------
    Radius:         279.84
    Length:         858.93
    ================================================
    Geometry - Tank
    ================================================
    Dimensions
    ------------------------------------------------
    Radius:         279.84
    Length:         858.93
    ================================================
    Values
    ------------------------------------------------
    Diameter:       559.68
    Circumference:  1758.2865763611353
    Cross Area:     246019.45776445002
    Lateral Area:   1510245.0890338698
    Central Volume: 211313492.85761905
    Width.Text:     559.68
    Lateral Length: 1418.61
    Total Area:     2494322.92009167
    Total Volume:   303108272.93869066
    ================================================
    
    Press any key to close this window . . .
  52. To close the window and return to your programming environment, press W
  53. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
  54. Make sure Console App is selected. Click Next
  55. Change the project Name to Volumetrics5 and change or accept the project Location
  56. Click Next
  57. Make sure the Framework combo box is displaying .NET 8.0 (Long-Term Support). Press Enter
  58. To create a new folder, in the Solution Explorer, right-click Volumetrics5 -> Add -> New Folder
  59. Type Models as the name of the folder
  60. In the Solution Explorer, right-click Models -> Add -> Add Class...
  61. Change the file name to Circle
  62. Click Add

Returning this Object

You may remember that a method of a class can return this object that represents the class itself. Here is an example:

internal class Triangle
{
    public void Examine()
    {
        Triangle inside = this;
    }
}

Practical LearningPractical Learning: Returning this Object

  1. Change the document as follows:

    Square

    namespace Volumetrics5.Models
    {
        internal class Circle
        {
            public double Radius { get; set; }
    
            public Circle(double radius)
            {
                Radius = radius;
            }
    
            public double Diameter => Radius * 2.00;
            public double Circumference => Diameter * 3.141592653589793238462643;
            public double Area => Radius * Radius * 3.141592653589793238462643;
    
            public Circle Encircle()
            {
                return this;
            }
        }
    }
  2. In the Solution Explorer, right-click Models -> Add -> Class...
  3. In the middle list of the Add New Item dialog box, make sude Class is selected. Change the name of the class to Cone
  4. Click Add
  5. Cchange thea class as follows:

    Square

    namespace Volumetrics5.Models
    {
        internal class Cone : Circle
        {
            public double Height { get; set; }
    
            public Cone(double radius, double height) : base(radius)
            {
                Height = height;
            }
    
            public double BaseArea => Area;
            public double Volume   => Radius * Radius * Height * 3.141592653589793238462643 / 3.00;
        }
    }

Getting this Parent

A method of an inherited class can return this. You must then identify the role of this object as it is used in a derived class.

Practical LearningPractical Learning: Getting this Parent

  1. In the Cone class, create two methods as follows:
    namespace Volumetrics5.Models
    {
        internal class Cone : Circle    
        {
            public double Height { get; set; }
    
            public Cone(double radius, double height) : base(radius)
            {
                Height = height;
            }
    
            public double BaseArea => Area;
            public double Volume   => Radius * Radius * Height * 3.141592653589793238462643 / 3.00;
    
            public Circle Create()
            {
                return this;
            }
    
            public Cone Surround()
            {
                return this;
            }
        }
    }
  2. In the Solution Explorer, right-click Program.cs and click Rename
  3. Type Geometry (to get Geometry.cs) and press Enter
  4. On the message box, click Yes
  5. Click the Geometry.cs tab and change the document as follows:
    using static System.Console;
    using Volumetrics5.Models;
    
    Cone dongle = new Cone(0.00, 0.00);
    Circle c = dongle.Create();
    double radius = 0.00, height = 0.00;
    
    WriteLine("================================================");
    WriteLine("Geometry - Cone");
    WriteLine("================================================");
    WriteLine("Enter the values to process a cone");
    WriteLine("------------------------------------------------");
    
    try
    {
        Write("Base Radius:   ");
        radius = double.Parse(ReadLine()!);
    }
    catch (FormatException fe)
    {
        WriteLine("An error was produced when requesting the radius of the base of the cylinder." + Environment.NewLine +
                  "The error to report is: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Height:        ");
        height = double.Parse(ReadLine()!);
    }
    catch (FormatException fe)
    {
        WriteLine("An error was produced when requesting the height of the cylinder." + Environment.NewLine +
                  "The error to report is: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    Circle round = new Circle(radius);
    dongle = new Cone(radius, height);
    
    c = dongle.Create();
    
    WriteLine("================================================");
    WriteLine("Geometry - Cone");
    WriteLine("================================================");
    WriteLine("Dimensions");
    WriteLine("------------------------------------------------");
    WriteLine("Radius:        {0}", round.Radius);
    WriteLine("Height:        {0}", dongle.Height);
    WriteLine("================================================");
    WriteLine("Values");
    WriteLine("------------------------------------------------");
    WriteLine("Diameter:      {0}", c.Diameter);
    WriteLine("Circumference: {0}", c.Circumference);
    WriteLine("Base Area:     {0}", c.Area);
    WriteLine("Volume:        {0}", dongle.Volume);
    WriteLine("================================================");
  6. To execute the application, press Ctrl + F5:
  7. When requested, type the Base Radius as 84.79 and press Enter
  8. Type the Height as 375.67 and press Enter:
    ================================================
    Geometry - Cone
    ================================================
    Enter the values to process a cone
    ------------------------------------------------
    Base Radius:   84.79
    Height:        375.67
    ================================================
    Geometry - Cone
    ================================================
    Dimensions
    ------------------------------------------------
    Radius:        84.79
    Height:        375.67
    ================================================
    Values
    ------------------------------------------------
    Diameter:      169.58
    Circumference: 532.7512821957572
    Base Area:     22585.990608689128
    Volume:        2828293.0306554153
    ================================================
    
    Press any key to close this window . . .
  9. Return to your programming environment
  10. Change the code of the Geometry.cs document as follows:
    using static System.Console;
    using Volumetrics5.Models;
    
    WriteLine("================================================");
    WriteLine("Geometry - Cone");
    WriteLine("================================================");
    WriteLine("Enter the values to process a cone");
    WriteLine("------------------------------------------------");
    
    double top    = 0.00;
    double bottom = 0.00;
    double height = 0.00;
    double length = 0.00;
    double radius
    
    try
    {
        Write("Base Radius:   ");
        radius = double.Parse(ReadLine()!);
    }
    catch (Exception ex) when (ex is FormatException fe)
    {
        WriteLine("An error was produced when requesting the radius of the base of the cylinder." + Environment.NewLine +
                  "The error to report is: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    try
    {
        Write("Height:        ");
        height = double.Parse(ReadLine()!);
    }
    catch (Exception ex) when (ex is FormatException fe)
    {
        WriteLine("An error was produced when requesting the height of the cylinder." + Environment.NewLine +
                  "The error to report is: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    Cone dongle = new Cone(radius, height);
    Cone fancy = dongle.Surround();
    
    WriteLine("================================================");
    WriteLine("Geometry - Cone");
    WriteLine("================================================");
    WriteLine("Dimensions");
    WriteLine("------------------------------------------------");
    WriteLine("Radius:        {0}", dongle.Radius);
    WriteLine("Height:        {0}", dongle.Height);
    WriteLine("================================================");
    WriteLine("Values");
    WriteLine("------------------------------------------------");
    WriteLine("Diameter:      {0}", fancy.Diameter);
    WriteLine("Circumference: {0}", fancy.Circumference);
    WriteLine("Base Area:     {0}", fancy.Area);
    WriteLine("Volume:        {0}", fancy.Volume);
    WriteLine("================================================");
  11. To execute the application and make sure it doesn't have an error, on the main menu, click Debug -> Start Without Debugging
  12. When requested, for the Base Radius, type 582.63 and press Enter
  13. For the Height, type 869.97 and press Enter:
    ================================================
    Geometry - Cone
    ================================================
    Enter the values to process a cone
    ------------------------------------------------
    Base Radius:   582.63
    Height:        869.97
    ================================================
    Geometry - Cone
    ================================================
    Dimensions
    ------------------------------------------------
    Radius:        582.63
    Height:        869.97
    ================================================
    Values
    ------------------------------------------------
    Diameter:      1165.26
    Circumference: 3660.772255522042
    Base Area:     1066437.8696174037
    Volume:        309256317.81035095
    ================================================
    
    Press any key to close this window . . .
  14. Return to your programming environment

Comparing an Object to this Parent

You can compare an object to this to find out what that object represents. This operation can be used to find out if an object refers to a parent, grand-parent, etc, of the object.

How "this" and "base" Objects are Similar and Different

The this and the base keywords live in a strange world. They have simmilarities and differences. Consider the following program:

using static System.Console;

Rectangle rect = new Rectangle();

rect.Side = 248.97;
rect.Height = 69.37;

Write("Length: ");
WriteLine(rect.Side);
Write("Height: ");
WriteLine(rect.Height);
Write("Area:   ");
WriteLine(rect.RectArea);
WriteLine("========================");

internal class Square
{
    double len;

    public double Side
    {
        get { return  len; }
        set { len = value; }
    }

    public double SquareArea
    {
        get { return Side * Side; }
    }
}

internal class Rectangle : Square
{
    double hgt;

    public double Height
    {
        get { return  hgt; }
        set { hgt = value; }
    }

    public double RectArea
    {
        get
        {   
            return Side * Height;
        }
    }
}

This would produce:

Length: 248.97
Height: 69.37
Area:   17271.0489
========================
Press any key to continue . . .

As one of the similarities, if you create a class that is based on another class, if the parent and the child classes don't have a member that uses the same name (in which case you would have a member in the child class and that member with that same name also exists in the parent class), both the this and the base keywords can be used interchangeably in the child class. In this case, both keywords would point to the same member, because that member is unique in both classes. Consider the following example:

internal class Square
{
    double len;

    public double Side
    {
        get { return  len; }
        set { len = value; }
    }

    public double SquareArea
    {
        get { return Side * Side; }
    }
}

internal class Rectangle : Square
{
    double hgt;

    public double Height
    {
        get { return  hgt; }
        set { hgt = value; }
    }

    public double RectArea
    {
        get
        {   /* On the following lines, either the "this" or the "base"
             * keywords can be use and they have the exact same effect. */ 
            return base.Side * Height;
            return this.Side * Height;
        }
    }
}

In the above case, either of these keywords is useless.

One of the differentces between the this and the base keywords is that, while the this keyword can be used in any non-static class, the base keyword can be used only in derived classes. Another difference is that, in a derived class in which you pass a certain parameter to a constructor and that parameter must represent a member (field or property) of a parent class, only the base keyword, and not the this object, can help you identify the member of the parent class. Consider the following example:

internal class Square
{
    double len;

    public Square(double side)
    {
    }
}

internal class Rectangle : Square
{
    public Rectangle(double width, double height)
         : base(width) // This will not work: : this(width)
    {
        Height = height;
    }

    public double Height
    {
        get { return  hgt; }
        set { hgt = value; }
    }
}

Probably the most important aspect that distinguishes the this and the base keywords is this: If you have a parent and a child classes and both have a member that uses the same name, if you want to access the parent member in the child class, in the child class, you must precede the name of the parent member with base.. Here is an example:

internal class Trapezoid
{
    public double TopBase { get; set; }
    public double BottomBase { get; set; }
    public double Height { get; set; }

    // This (parent) class contains a property named Area
    public double Area => Height * (TopBase + BottomBase) / 2.00;
}

internal class TrapezoidalPrism : Trapezoid
{
    public double Length { get; set; }
    
    // This child class also contains a property named Area
    public new double Area
    {
        get
        {
            return BaseArea + TopArea + BottomArea + BaseArea;
        }
    }

    public double BaseArea
    {
        /* Here, the "base" keyword must be used to indicate that you are 
         * accessing a member from the parent class while this class also
         * contains a member that has the same name as a member from the parent class. */
        get => base.Area;
    }
    
    /* In the following properties, either the "this" or the "base" keyword can be used or 
     * simply be omitted because there is no confusion about the member that is accessed. */ 
    public double TopArea    { get => this.TopBase * this.Length; }
    public double BottomArea { get => this.BottomBase * this.Length; }
})

The new Modifier

Introduction

Imagine you create a class, such as one for a geometric shape such as a trapezoid. As we saw above, you can use such a class as the base class for a prism. Both the trapezoid and its related prism have an area but their areas are different.

If you create or declare a new member in a derived class and that member has the same name as a member of the base class, when creating the new member, you may want to indicate to the compiler that you want to create a brand new and independent version of that method. When doing this, you would be asking the compiler to hide the member of the base class that has the same name, when the member of the current class is invoked.

Creating a New Version of a Member of a Class

To create a new version of a member, type the new keyword to its left.

ApplicationPractical Learning: Creating a New Version of a Member

  1. On the main menu, click File -> Recent Projects and Solutions -> ...Volumetrics3 project created earlier
  2. Click the TrapezoidalPrism.cs tab and add a new method in the class as follows:
    namespace Volumetrics5.Models
    {
        internal class TrapezoidalPrism : Trapezoid
        {
            private double len;
    
            // "this" refers to a local property
            public TrapezoidalPrism(double top, double bottom, double height, double length)
                    : base(top, bottom, height) => this.Length = length;
    
            public double Length
            {
                // "this" refers to a local field
                get => this.len;
    
                // "this" refers to a local field
                set => this.len = value;
            }
    
            public double BaseArea
            {
                // "base" refers to a parent
               get => base.Area;
            }
    
            public double TopArea
            {
                // "this" TopBase refers to a parent's property
                // "this" refers to a local property
                get => this.TopBase * this.Length;
            }
    
            public double BottomArea
            {
                // "this" BottomBase refers to a parent's property
                // "this" refers to a local property
                get => this.BottomBase * this.Length;
            }
    
            public new double Area
            {
                get
                {
                    return BaseArea + TopArea + BottomArea + BaseArea;
                }
            }
    
            public double Volume
            {
                // "base" Area refers to a parent's property
                // "this" refers to a local property
                get => base.Area * this.Length;
            }
        }
    }
  3. Click the Geometry.cs tab to access the file
  4. Change the document as follows:
    using static System.Console;
    using Volumetrics3.Models;
    
    TrapezoidalPrism Prepare()
    {
        WriteLine("================================================");
        WriteLine("Geometry - Trapezoidal Prism");
        WriteLine("================================================");
        WriteLine("Enter the values to process a trapezoidal prism");
        WriteLine("------------------------------------------------");
        
        double top    = 0.00;
        double bottom = 0.00;
        double height = 0.00;
        double length = 0.00;
    
        try
        {
            Write("Top Base:    ");
            top = double.Parse(ReadLine()!);
        }
        catch (Exception ex) when (ex is FormatException fe)
        {
            WriteLine("There was an error for the value of the top base." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        try
        {
            Write("Bottom Base: ");
            bottom = double.Parse(ReadLine()!);
        }
        catch (Exception ex) when (ex is FormatException fe)
        {
            WriteLine("There was an error for the value of the bottom base." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        try
        {
            Write("Height:      ");
            height = double.Parse(ReadLine()!);
        }
        catch (Exception ex) when (ex is FormatException fe)
        {
            WriteLine("There was an error for the value of the height." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        try
        {
            Write("Length:      ");
            length = double.Parse(ReadLine()!);
        }
        catch (Exception ex) when (ex is FormatException fe)
        {
            WriteLine("There was an error for the value of the length." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        return new TrapezoidalPrism(top, bottom, height, length);
    }
    
    static void Present(TrapezoidalPrism trap)
    {
        WriteLine("================================================");
        WriteLine("Geometry - Trapezoidal Prism");
        WriteLine("================================================");
        WriteLine("Dimensions");
        WriteLine("------------------------------------------------");
        WriteLine("Top Base:    {0}", trap.TopBase);
        WriteLine("Bottom Base: {0}", trap.BottomBase);
        WriteLine("Height:      {0}", trap.Height);
        WriteLine("Length:      {0}", trap.Length);
        WriteLine("================================================");
        WriteLine("Areas");
        WriteLine("------------------------------------------------");
        WriteLine("Base Area:   {0}", trap.BaseArea);
        WriteLine("Top Area:    {0}", trap.TopArea);
        WriteLine("Bottom Area: {0}", trap.BottomArea);
        WriteLine("Total Area:  {0}", trap.Area);
        WriteLine("------------------------------------------------");
        WriteLine("Volume:      {0}", trap.Volume);
        WriteLine("================================================");
    }
    
    TrapezoidalPrism tp = Prepare();
    
    Present(tp);
  5. To execute the application, on the menu, click Debug -> Start Without Debugging:
  6. For the Top Base, type 137.96 and press Enter
  7. For the Bottom Base, type 209.73 and press Enter
  8. For the Height, type 87.59 and press Enter
  9. For the Length, type 142.46 and press Enter:
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Enter the values to process a trapezoidal prism
    ------------------------------------------------
    Top Base:    137.96
    Bottom Base: 209.73
    Height:      87.59
    Length:      142.46
    ================================================
    Geometry - Trapezoidal Prism
    ================================================
    Dimensions
    ------------------------------------------------
    Top Base:    137.96
    Bottom Base: 209.73
    Height:      87.59
    Length:      142.46
    ================================================
    Areas
    ------------------------------------------------
    Base Area:   15227.083550000001
    Top Area:    19653.781600000002
    Bottom Area: 29878.1358
    Total Area:  79986.0845
    ------------------------------------------------
    Volume:      2169250.3225330003
    ================================================
    
    Press any key to close this window . . .
  10. To close the window and return to your programming environment, press X
  11. Close your programming environment

Previous Copyright © 2001-2024, FunctionX Sunday 30 April 2023 Next