Inheritance With the Base Class

Introduction

Object-oriented programming (OOP) consists of creating an application that uses relatively small objects that are created from classes. To perform OOP, we have learned to create classes and derive classes from them. OOP is not just about creating classes; it is also how you manage those classes with themselves but also manage how objects interact with other objects.

Practical LearningPractical Learning: Introducing Base Classes

  1. Save the following images to your computer:

    Square

    Square

  2. Start Microsoft Visual Studio. Create a new ASP.NET Core Web App name with Volumetrics2 that supports the .NET 6.0 (Long-Term Support) and uncheck the Configure For HTTPS check box
  3. In the Solution Explorer, right-click Volumetrics2 -> Add -> New Folder
  4. Type Models
  5. In the Solution Explorer, right-click wwwroot -> Add -> New Folder
  6. Type images and press Enter
  7. In the Solution Explorer, under wwwroot, right-click images -> Add -> Existing Item...
  8. Select the images you had saved and Add them to the project
  9. In the Solution Explorer, expand wwwroot
  10. In the Solution Explorer, under wwwroot, right-click css -> Add -> New Item...
  11. In the left list of the Add New Item dialog box, under Visual C#, expand ASP.NET Core. Expand Web, and click Content
  12. In the middle list, click Style Sheet
  13. Change the file Name to Geometry
  14. Press Enter
  15. Change the document as follows:
    body {
    }
    
    .bold        { font-weight:      bold;  }
    .text-right  { text-align:       right  }
    .delimiter   { margin:           auto;
                   width:            650px; }
    .top-bar     { border-bottom:    6px solid blue;
                   background-color: #800000 !important; }
    .common-font { font-family:      Georgia, Garamond, 'Times New Roman', serif; }
    .navbar-light .navbar-brand       { color:       white;  }
    .navbar-light .navbar-brand:hover { color:       yellow; }
    .navbar-light .navbar-brand:focus { color:       khaki;  }
    .navbar-light .navbar-brand       { font-family: Georgia, Garamond, 'Times New Roman', serif; }
    .nav-link                         { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  16. In the Solution Explorer, under Pages, expand Shared
  17. In the Solution Explorer, under Pages and under Shared, double-click _Layout.cshtml
  18. Change the document as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - Geometry</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/css/Geometry.css" asp-append-version="true" />
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 top-bar">
                <div class="container">
                    <a class="navbar-brand" asp-area="" asp-page="/Index">Geometry</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/Privacy">Privacy</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                <p class="text-center common-font">&copy; 2022 - Geometry - Volumetrics - <a asp-area="" asp-page="/Privacy">Privacy</a></p>
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
  19. In the Solution Explorer, right-click Models -> Add -> Class...
  20. In the middle list of the Add New Item dialog box, make sure Class is selected.
    Change the Name of the file to Trapezoid
  21. Click Add
  22. Change the document as follows:
    namespace Volumetrics2.Models
    {
        public 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;
                }
            }
        }
    }
  23. In the Solution Explorer, expand Pages and double-click Index.cshtml
  24. Change the document as follows:
    @page
    @model IndexModel
    @using Volumetrics2.Models
    @{
        string? strMessage = null;
        Trapezoid trap = new Trapezoid();
    
        if (Request.HasFormContentType)
        {
            try
            {
                trap.TopBase = double.Parse(Request.Form["txtTopBase"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
    
            try
            {
                trap.BottomBase = double.Parse(Request.Form["txtBottomBase"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
    
            try
            {
                trap.Height = double.Parse(Request.Form["txtHeight"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Geometry - Trapezoid</h2>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 300px" rowspan="9">
                      <img src="~/images/trapezoid1.png" width="296" height="247" alt="Geometry - Trapezoid">
                  </td>
                  <td style="width: 125px" class="bold">Top Base:</td>
                  <td>@Html.TextBox("txtTopBase", @trap.TopBase, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Bottom Base:</td>
                  <td>@Html.TextBox("txtBottomBase", @trap.BottomBase, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Height:</td>
                  <td>@Html.TextBox("txtHeight", @trap.Height, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Calculate" /></td>
              </tr>
              <tr>
                  <td class="bold">Area:</td>
                  <td>@Html.TextBox("txtArea", @trap.Area, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
      </form>
    
      <hr />
      <p class="text-center">@strMessage</p>
    </div>
  25. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introducing Read-Write Properties

  26. In the text box, type the following values:
    Top Base:    137.96
    Bottom Base: 209.73
    Height:      87.59

    Introducing Read-Write Properties

  27. Click the Calculate button:

    Introducing Read-Write Properties

  28. Return to your programming environment, press Enter

Inheriting the Base Object

We learned that, one way to extend the functionality of a class is to create a new class derived from an existing class. When creating a derived class, to indicate that you are accessing the parent class, you can use a keyword named base. That jeyword 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. In the Solution Explorer, click-click Models -> Add -> Class...
  2. Type TrapezoidalPrism as the Name of the file
  3. Press Enter
  4. Change the class as follows:
    namespace Volumetrics2.Models
    {
        public 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;
                }
    	}
        }
    }
  5. Click the Index.cshtml tab to access the razor page
  6. Change the document as follows:
    @page
    @model IndexModel
    @using Volumetrics2.Models
    @{
        string? strMessage = null;
        TrapezoidalPrism trap = new TrapezoidalPrism();
    
        if (Request.HasFormContentType)
        {
            try
            {
                trap.TopBase = double.Parse(Request.Form["txtTopBase"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
            try
            {
                trap.BottomBase = double.Parse(Request.Form["txtBottomBase"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
            try
            {
                trap.Height = double.Parse(Request.Form["txtHeight"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
            try
            {
                trap.Length = double.Parse(Request.Form["txtLength"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Geometry - Trapezoidal Prism</h2>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 300px" rowspan="9">
                      <img src="~/images/tp.png" width="289" height="230" alt="Geometry - Trapezoidal Prism">
                  </td>
                  <td style="width: 125px" class="bold">Top Base:</td>
                  <td>@Html.TextBox("txtTopBase", @trap.TopBase, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Bottom Base:</td>
                  <td>@Html.TextBox("txtBottomBase", @trap.BottomBase, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Height:</td>
                  <td>@Html.TextBox("txtHeight", @trap.Height, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Length:</td>
                  <td>@Html.TextBox("txtLength", @trap.Length, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Calculate" /></td>
              </tr>
              <tr>
                  <td class="bold">Base Area:</td>
                  <td>@Html.TextBox("txt>BaseArea", @trap.BaseArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Top Area:</td>
                  <td>@Html.TextBox("txtTopArea", @trap.TopArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Bottom Area:</td>
                  <td>@Html.TextBox("txtBottomArea", @trap.BottomArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Volume:</td>
                  <td>@Html.TextBox("txtVolume", @trap.Volume, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
      </form>
    
      <hr />
      <p class="text-center">@strMessage</p>
    </div>
  7. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introducing Read-Write Properties

  8. In the text box, type the following values:
    Top Base:    137.96
    Bottom Base: 209.73
    Height:      87.59
    Length:      142.46

    Introducing Read-Write Properties

  9. Click the Calculate button:

    Introducing Read-Write Properties

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

public class Circle
{
    private double _radius;

    public Circle()
    {
        _radius = 0.00;
    }
}

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

public class Circle
{
    private double _radius;

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

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

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

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

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

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

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

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

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

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

public 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 Volumetrics2.Models
    {
        public 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 Volumetrics2.Models
    {
        public 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 Index.cshtml tab to access the file
  6. Change the code as follows:
    @page
    @model IndexModel
    @using Volumetrics2.Models
    @{
        string? strMessage = null;
        TrapezoidalPrism? trap = null;
    
        if (Request.HasFormContentType)
        {
            double top = 0.00;
            double bottom = 0.00;
            double height = 0.00;
            double length = 0.00;
    
            try
            {
                top = double.Parse(Request.Form["txtTopBase"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
    
            try
            {
                bottom = double.Parse(Request.Form["txtBottomBase"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
    
            try
            {
                height = double.Parse(Request.Form["txtHeight"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
            try
            {
                length = double.Parse(Request.Form["txtLength"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
    
            trap = new TrapezoidalPrism(top, bottom, height, length);
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Geometry - Trapezoidal Prism</h2>
        <hr />
       <form name="frmGeometry" method="post">
          . . .
      </form>
    
      <hr />
      <p class="text-center">@strMessage</p>
    </div>
  7. To execute the application and test the form, press Ctrl + F5
  8. If the browser presemts a Resend button, click it, or refresh the browser
  9. Change the values in the text boxes as follows:
    Top Base:    588.97
    Bottom Base: 836.84
    Height:      1079.41
    Length:      1326.73
  10. Click the Calculate button:

    Introducing Read-Write Properties

  11. Return to your programming environment

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 Volumetrics2.Models
    {
        public 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. If the browser presents a Resend button, click it, or refresh the browser
  4. Change the values in the top text boxes as follows:
    Top Base:    357.93
    Bottom Base: 637.77
    Height:      2263.79
    Length:      975.86
  5. Click the Calculate button:

    Introducing Read-Write Properties

  6. Return to your programming environment
  7. Click the Trapezoid.cs tab to access the file
  8. Change the code of the Area as follows:
    namespace Volumetrics2.Models
    {
        public 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, BottomBase, Height) = (top, bottom, height);
            }
    
            public double Area => Height * (TopBase + BottomBase) / 2.00;
        }
    }
  9. Click the TrapezoidalPrism.cs tab to access its file
  10. Reduce its code as follows:
    namespace Volumetrics2.Models
    {
        public class TrapezoidalPrism : Trapezoid
        {
            private double len;
    
            public TrapezoidalPrism(double top, double bottom, double height, double length)
                    : base(top, bottom, height) => this.Length = length;
    
            public double Length
            {
                get => this.len;
                set => this.len = value;
            }
    
            public double BaseArea
            {
                get => base.Area;
            }
    
            public double TopArea
            {
                get => this.TopBase * this.Length;
            }
    
            public double BottomArea
            {
                get => this.BottomBase * this.Length;
            }
    
            public double Volume
            {
                get => base.Area * this.Length;
            }
        }
    }
  11. To execute the application to test the code and make sure there is no error, press Ctrl + F5
  12. If the browser presents a Resend button, click it, or refresh the browser
  13. Close the browser and return to your programming environment
  14. Save the following images to your computer:

    Square

    Square

  15. Start a new ASP.NET Core Web App named Volumetrics3
  16. In the Solution Explorer, right-click Volumetrics3 -> Add -> New Folder
  17. Type Models
  18. In the Solution Explorer, right-click wwwroot -> Add -> New Folder
  19. Type images and press Enter
  20. In the Solution Explorer, under wwwroot, right-click images -> Add -> Existing Item...
  21. Select the above images you had saved and Add them to the project
  22. In the Solution Explorer, under wwwroot, right-click css -> Add -> New Item...
  23. In the left list of the Add New Item dialog box, under Visual C#, expand ASP.NET Core. Expand Web, and click Content
  24. In the middle list, click Style Sheet
  25. Change the file Name to Geometry
  26. Press Enter
  27. Change the document as follows:
    body {
    }
    
    .bold        { font-weight:      bold;  }
    .text-right  { text-align:       right  }
    .delimiter   { margin:           auto;
                   width:            650px; }
    .top-bar     { border-bottom:    6px solid blue;
                   background-color: navy !important; }
    .common-font { font-family:      Georgia, Garamond, 'Times New Roman', serif; }
    .navbar-light .navbar-brand       { color:       white;  }
    .navbar-light .navbar-brand:hover { color:       yellow; }
    .navbar-light .navbar-brand:focus { color:       khaki;  }
    .navbar-light .navbar-brand       { font-family: Georgia, Garamond, 'Times New Roman', serif; }
    .nav-link                         { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  28. In the Solution Explorer, under Pages, expand Shared
  29. In the Solution Explorer, under Pages and under Shared, double-click _Layout.cshtml
  30. Change the document as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - Geometry</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/css/Geometry.css" asp-append-version="true" />
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 top-bar">
                <div class="container">
                    <a class="navbar-brand" asp-area="" asp-page="/Index">Geometry</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/Privacy">Privacy</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                <p class="text-center common-font">&copy; 2022 - Geometry - Volumetrics - <a asp-area="" asp-page="/Privacy">Privacy</a></p>
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
  31. In the Solution Explorer, right-click 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:
    namespace Volumetrics3.Models
    {
        public class Cylinder
        {
            public double Length { get; set; }
            public double Radius { get; set; }
    
            public double Diameter
            {
                get
                {
                    return this.Radius * 2.00;
                }
            }
    
            public double Circumference
            {
                get
                {
                    return this.Diameter * 3.141592653589793238462643;
                }
            }
            
            public double CrossArea
            {
                get
                {
                    return this.Radius * this.Radius * 3.141592653589793238462643;
                }
            }
            
            public double LateralArea
            {
                get
                {
                    return this.Circumference * this.Length;
                }
            }
    
            public double CentralVolume
            {
                get
                {
                    return this.CrossArea * this.Length;
                }
            }
        }
    }
  35. In the Solution Explorer, under Pages, right-click Index.cshtml -> Open
  36. Change the document as follows:
    @page
    @model IndexModel
    @using Volumetrics3.Models
    @{
        string? strMessage = null;
        Cylinder vol = new Cylinder();
    
        if (Request.HasFormContentType)
        {
            try
            {
                vol.Length = double.Parse(Request.Form["txtLength"]);
            }
            catch(FormatException fexc)
            {
                strMessage = "You must provide a valid value for the length (or height)  of the cylinder. " + 
                             Environment.NewLine +
                             "The error produced is: " + fexc.Message;
            }
    
            try
            {
                vol.Radius = double.Parse(Request.Form["txtRadius"]);
            }
            catch(FormatException fexc)
            {
                strMessage = "You must provide a valid value for the radius of the cylinder. " + 
                             Environment.NewLine +
                             "The error produced is: " + fexc.Message;
            }
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Geometry - Cylinder</h2>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 300px" rowspan="9">
                      <img src="~/images/cylinder.png" width="261" height="281 alt="Geometry - Cylinder">
                  </td>
                  <td style="width: 125px" class="bold">Length:</td>
                  <td>@Html.TextBox("txtLength", @vol.Length, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Radius:</td>
                  <td>@Html.TextBox("txtRadius", @vol.Radius, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Calculate" /></td>
              </tr>
              <tr>
                  <td class="bold">Diameter:</td>
                  <td>@Html.TextBox("txtDiameter", @vol.Diameter, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Circumference:</td>
                  <td>@Html.TextBox("txtCircumference", @vol.Circumference, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Cross Area:</td>
                  <td>@Html.TextBox("txtCrossArea", @vol.CrossArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Lateral Area:</td>
                  <td>@Html.TextBox("txtLateralArea", @vol.LateralArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Central Volume:</td>
                  <td>@Html.TextBox("txtCentralVolume", @vol.CentralVolume, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
      </form>
    
      <hr />
    
      <p class="text-center">@strMessage</p>
    </div>
  37. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introducing Read-Write Properties

  38. In the top text box, type the following values:
    Top Base: 79.84
    Length:   258.93

    Introducing Read-Write Properties

  39. Click the Calculate button:

    Introducing Read-Write Properties

  40. Return to your programming environment, press Z
  41. To add a class, in the Solution Explorer, click Models -> Add -> Class...
  42. Make sure Class is selected in the middle list. Change the name of the file to Tank
  43. Click Add
  44. Change the document as follows:
    namespace Volumetrics3.Models
    {
        public 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 * PI * 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);
            }
        }
    }
  45. Click the Index.cshtml tab
  46. Change the document as follows:
    @page
    @model IndexModel
    @using Volumetrics3.Models
    @{
        string? strMessage = null;
        Tank vol = new Tank();
    
        if (Request.HasFormContentType)
        {
            try
            {
                vol.Length = double.Parse(Request.Form["txtLength"]);
            }
            catch(FormatException fexc)
            {
                strMessage = "You must provide a valid value for the length (or height)  of the cylinder. " + 
                             Environment.NewLine +
                             "The error produced is: " + fexc.Message;
            }
    
            try
            {
                vol.Radius = double.Parse(Request.Form["txtRadius"]);
            }
            catch(FormatException fexc)
            {
                strMessage = "You must provide a valid value for the radius of the cylinder. " + 
                             Environment.NewLine +
                             "The error produced is: " + fexc.Message;
            }
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Geometry - Tank</h2>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 430px" rowspan="12">
                      <img src="~/images/tank.png" width="428" height="235" alt="Geometry - Tank">
                  </td>
                  <td class="bold">Length:</td>
                  <td>@Html.TextBox("txtLength", @vol.Length, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Radius:</td>
                  <td>@Html.TextBox("txtRadius", @vol.Radius, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Calculate" /></td>
              </tr>
              <tr>
                  <td class="bold">Diameter:</td>
                  <td>@Html.TextBox("txtDiameter", @vol.Diameter, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Circumference:</td>
                  <td>@Html.TextBox("txtCircumference", @vol.Circumference, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Cross Area:</td>
                  <td>@Html.TextBox("txtCrossArea", @vol.CrossArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Lateral Area:</td>
                  <td>@Html.TextBox("txtLateralArea", @vol.LateralArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Central Volume:</td>
                  <td>@Html.TextBox("txtCentralVolume", @vol.CentralVolume, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Width:</td>
                  <td>@Html.TextBox("txtWidth", @vol.Width, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Total Length:</td>
                  <td>@Html.TextBox("txtTotalLength", @vol.TotalLength, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Total Area:</td>
                  <td>@Html.TextBox("txtTotalArea", @vol.TotalArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Total Volume:</td>
                  <td>@Html.TextBox("txtTotalVolume", @vol.TotalVolume, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
      </form>
    
      <hr />
    
      <p class="text-center">@strMessage</p>
    </div>
  47. To execute the project, on the main menu, click Debug -> Start Without Debugging
  48. If the browser presents a Resend button, click it, or refresh the browser:

    Introducing Read-Write Properties

  49. Return to your programming environment
  50. Click the Cylinder.cshtml tab and change its class as follows:
    namespace Volumetrics3.Models
    {
        public 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;
        }
    }
  51. Click the Tank.cshtml tab and change the class follows:
    namespace Volumetrics3.Models
    {
        public class Tank : Cylinder
        {
            public double Width
            {
                get => this.Diameter;
            }
    
            public double TotalLength
            {
                get => this.Length + this.Radius + this.Radius;
            }
    
            public double TotalArea
            {
                // 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
                get => this.LateralArea + (this.Radius * this.Radius * 3.141592653589793238462643 * 4.00);
            }
    
            public double TotalVolume
            {
                // 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)
                get => this.CentralVolume + (this.Radius * this.Radius * this.Radius * 3.141592653589793238462643 * 4.00 / 3.00);
            }
        }
    }
  52. To execute again, on the main menu, click Debug -> Start Without Debugging
  53. If the browser presents a Resend button, click it, or refresh the browser
  54. Change the Radius to 279.84
  55. Change the Length to 858.93
  56. Click the Calculate button:

    Introducing Read-Write Properties

  57. Return to your programming environment

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:

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

Consider a class as follows:

Square

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

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. This can be done as follows:

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

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 code in a razor page:

@page
@model Valuable.Pages.ExceptionsModel
@{
    Rectangle rect = new Rectangle();
    
    rect.Side = 248.97;
    rect.Height = 69.37;
}

@functions{
    public class Square
{
    double len;

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

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

public class Rectangle : Square
{
    double hgt;

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

    public double RectArea
    {
        get
        {   
            return Side * Height;
        }
    }
}
}
<h3>Geometry -  Rectangle</h3>
<hr />
<table>
    <tr>
        <td style="width: 100px">Length:</td>
        <td>@rect.Side</td>
    </tr>
    <tr>
        <td>Height:</td>
        <td>@rect.Height</td>
    </tr>
    <tr>
        <td>Area:</td>
        <td>@rect.RectArea</td>
    </tr>
</table>

This would produce:

Geometry - Rectangle
Length: 	248.97
Height: 	69.37
Area: 	17271.0489

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:

public class Square
{
    double len;

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

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

public 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 differences 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:

public class Square
{
    double len;

    public Square(double side)
    {
    }
}

public class Rectangle : Square
{
    double hgt;

    public Rectangle(double width, double height)
         : base(width) // This will not work: : this(width)
    {
        hgt = 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:

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

public 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 -> \...\Volumetrics2
  2. Click the TrapezoidalPrism.cs tab and add a new method in the class as follows:
    namespace Volumetrics2.Models
    {
        public 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 Index.cshtml tab to access the razor page
  4. Change the document as follows:
    @page
    @model IndexModel
    @using Volumetrics2.Models
    @{
        string? strMessage = null;
        TrapezoidalPrism trap = new(0.00, 0.00, 0.00, 0.00);
    
        if (Request.HasFormContentType)
        {
            double top    = 0.00;
            double bottom = 0.00;
            double height = 0.00;
            double length = 0.00;
    
            try
            {
                top = double.Parse(Request.Form["txtTopBase"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
    
            try
            {
                bottom = double.Parse(Request.Form["txtBottomBase"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
    
            try
            {
                height = double.Parse(Request.Form["txtHeight"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
            try
            {
                length = double.Parse(Request.Form["txtLength"]);
            }
            catch(FormatException fexc)
            {
                strMessage = fexc.Message;
            }
    
            trap = new(top, bottom, height, length);
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Geometry - Trapezoidal Prism</h2>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 300px" rowspan="10">
                      <img src="~/images/tp.png" width="296" height="247" alt="Geometry - Trapezoidal Prism">
                  </td>
                  <td style="width: 125px" class="bold">Top Base:</td>
                  <td>@Html.TextBox("txtTopBase", @trap.TopBase, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Bottom Base:</td>
                  <td>@Html.TextBox("txtBottomBase", @trap.BottomBase, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Height:</td>
                  <td>@Html.TextBox("txtHeight", @trap.Height, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Length:</td>
                  <td>@Html.TextBox("txtLength", @trap.Length, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Calculate" /></td>
              </tr>
              <tr>
                  <td class="bold">Base Area:</td>
                  <td>@Html.TextBox("txtArea", @trap.Area, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Top Area:</td>
                  <td>@Html.TextBox("txtTopArea", @trap.TopArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Bottom Area:</td>
                  <td>@Html.TextBox("txtBottomArea", @trap.BottomArea, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Total Area:</td>
                  <td>@Html.TextBox("txtArea", @trap.Area, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td class="bold">Volume:</td>
                  <td>@Html.TextBox("txtVolume", @trap.Volume, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
      </form>
    
      <hr />
      <p class="text-center">@strMessage</p>
    </div>
  5. To execute the application, on the menu, click Debug -> Start Without Debugging
  6. Set the values as follows:
    Top Base:    586.77
    Bottom Base: 939.61
    Height:      473.97
    Length:      884.39
  7. Click the Calculate button:

    Introducing Read-Write Properties

  8. To close the window and return to your programming environment, press X
  9. Close your programming environment

Previous Copyright © 2001-2022, FunctionX Friday 26 November 2021 Next