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. Save the following image somewhere on your computer:

    Trapezoidal Prism

  2. Start Microsoft Visual Studio. On the Visual Studio 2019 dialog box, click Create a New Project (if Microsoft Visual Studio was already running, on the main menu, click File -> New -> Project...)
  3. In the list of projects templates, click Windows Forms App (.NET Framework)
  4. Click Next
  5. Replace the suggested project name with Geometry12
  6. Click Create
  7. In the Solution Explorer, right-click Geometry09 -> Add -> Class...
  8. Change the name of the file to Trapezoid
  9. Click Add
  10. Change the document as follows:
    namespace Geometry12
    {
        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;
                }
            }
        }
    }
  11. In the Solution Explorer, right-click Geometry09 -> Add -> Class...
  12. Change the name of the class as TrapezoidalPrism
  13. Click Add
  14. Fill the class as follows:
    namespace Geometry12
    {
        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;
                }
            }
        }
    }
  15. In the Solution Explorer, right-click Form1.cs -> Open
  16. Add a PictureBox to the form and, in the Properties window, set its Image property to the above geometric figure
  17. Complete the design of the form as follows:

    Accessing the Base Object from a Child Class

    Control (Name) Text
    PictureBox    
    Label   Top Base:
    TextBox txtTopBase  
    Label   Bottom Base:
    TextBox txtBottomBase  
    Label   Height:
    TextBox txtHeight  
    Label   Length
    TextBox txtLength  
    Button btnCalculate Calculate
    Label   Base Area:
    TextBox txtBaseArea  
    Label   Top Area:
    TextBox txtTopArea  
    Label   Bottom Area:
    TextBox txtBottomArea  
    Label   Volume:
    TextBox txtVolume  
  18. Double-click the Calculate button
  19. Right-click inside the Code Editor and click Remove and Sort Usings
  20. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry12
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double top = 0.00;
                double bottom = 0.00;
                double height = 0.00;
                double length = 0.00;
    
                TrapezoidalPrism tp = new TrapezoidalPrism();
    
                try
                {
                    top = double.Parse(txtTopBase.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try
                {
                    bottom = double.Parse(txtBottomBase.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try
                {
                    height = double.Parse(txtHeight.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try
                {
                    length = double.Parse(txtLength.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                tp.TopBase = top;
                tp.BottomBase = bottom;
                tp.Height = height;
                tp.Length = length;
    
                txtBaseArea.Text = tp.BaseArea.ToString();
                txtTopArea.Text = tp.TopArea.ToString();
                txtBottomArea.Text = tp.BottomArea.ToString();
                txtVolume.Text = tp.Volume.ToString();
            }
        }
    }
  21. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Displaying a Picture in a Control

  22. In the Top Base text box, enter a number such as 137.96
  23. In the Bottom Base text box, enter a number such as 209.73
  24. In the Height text box, enter a number such as 87.59
  25. In the Length text box, enter a number such as 142.46

    Displaying a Picture in a Control

  26. Click the Calculate button:

    Displaying a Picture in a Control

  27. Close the form and return to your programming environment

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 Geometry12
    {
        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 Geometry12
    {
        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 Form1.cs tab to access the file of the form
  6. Change the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry12
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double top = 0.00;
                double bottom = 0.00;
                double height = 0.00;
                double length = 0.00;
    
                try
                {
                    top = double.Parse(txtTopBase.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try { bottom = double.Parse(txtBottomBase.Text); }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try
                {
                    height = double.Parse(txtHeight.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try
                {
                    length = double.Parse(txtLength.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                TrapezoidalPrism tp = new TrapezoidalPrism(top, bottom, height, length);
    
                Present(tp);
            }
    
            void Present(TrapezoidalPrism shape)
            {
                txtBaseArea.Text = shape.BaseArea.ToString();
                txtTopArea.Text = shape.TopArea.ToString();
                txtBottomArea.Text = shape.BottomArea.ToString();
                txtVolume.Text = shape.Volume.ToString();
            }
        }
    }
  7. To execute the application and test the form, press Ctrl + F5
  8. Close the form and 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 Geometry12
    {
        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. Close the form and return to your programming environment
  4. Click the Trapezoid.cs tab to access the file
  5. Add a constructor to the class as follows:
    namespace Geometry12
    {
        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 => Height * (TopBase + BottomBase) / 2.00;
        }
    }
  6. Click the TrapezoidalPrism.cs tab to access its file
  7. Create a constructor in the class as follows:
    namespace Geometry12
    {
        public 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;
            }
        }
    }
  8. Click the Form1.cs tab to access the file of the form
  9. Change the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry12
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double top = 0.00;
                double bottom = 0.00;
                double height = 0.00;
                double length = 0.00;
    
                try
                {
                    top = double.Parse(txtTopBase.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try { bottom = double.Parse(txtBottomBase.Text); }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try
                {
                    height = double.Parse(txtHeight.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                try
                {
                    length = double.Parse(txtLength.Text);
                }
                catch (FormatException exc)
                {
                    MessageBox.Show(exc.Message, "Geometry");
                }
    
                TrapezoidalPrism tp = new TrapezoidalPrism(top, bottom, height, length);
    
                Present(tp);
            }
    
            void Present(TrapezoidalPrism shape)
            {
                txtBaseArea.Text = shape.BaseArea.ToString();
                txtTopArea.Text = shape.TopArea.ToString();
                txtBottomArea.Text = shape.BottomArea.ToString();
                txtVolume.Text = shape.Volume.ToString();
            }
        }
    }
  10. To execute the application and test the form, press Ctrl + F5
  11. Close the form and return to your programming environment
  12. Click the TrapezoidalPrism.cs tab to access its file
  13. Create a constructor in the class as follows:
    namespace Geometry12
    {
        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 double Volume
            {
                // "base" Area refers to a parent's property
                // "this" refers to a local property
                get => base.Area * this.Length;
            }
        }
    }
  14. Click the Form1.cs tab to access the file of the form
  15. Change the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry12
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            TrapezoidalPrism Prepare()
            {
                double top = 0.00;
                double bottom = 0.00;
                double height = 0.00;
                double length = 0.00;
    
                try
                {
                    top = double.Parse(txtTopBase.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the top base", "Geometry");
                }
    
                try { bottom = double.Parse(txtBottomBase.Text); }
                catch (FormatException)
                {
                    MessageBox.Show("The value you specified for the bottom base is not valie", "Geometry");
                }
    
                try
                {
                    height = double.Parse(txtHeight.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Either you didn't provide a value for the height or you left it empty.", "Geometry");
                }
    
                try
                {
                    length = double.Parse(txtLength.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Please make sure you enter an appropriate value for the length.", "Geometry");
                }
    
                return new TrapezoidalPrism(top, bottom, height, length);
    
            }
            
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                TrapezoidalPrism tp = Prepare();
    
                Present(tp);
            }
    
            void Present(TrapezoidalPrism shape)
            {
                txtBaseArea.Text = shape.BaseArea.ToString();
                txtTopArea.Text = shape.TopArea.ToString();
                txtBottomArea.Text = shape.BottomArea.ToString();
                txtVolume.Text = shape.Volume.ToString();
            }
        }
    }
  16. To execute the application and test the form, press Ctrl + F5
  17. Close the form and return to your programming environment
  18. Save the following picture somewhere on your computer:

    Geometry - Cylinder

  19. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  20. In the list of projects templates, click Windows Forms App (.NET Framework)
  21. Click Next
  22. Replace the name of the project with Geometry13
  23. Click Create
  24. In the Solution Explorer, right-click App_Code -> Add -> Class...
  25. Set the name of the class as Cylinder
  26. Click Add
  27. Fill the class as follows:
    using static System.Math;
    
    namespace Geometry13
    {
        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 * PI;
            public double CrossArea     => this.Radius * this.Radius * PI;
            public double LateralArea   => this.Circumference * this.Length;
            public double CentralVolume => this.CrossArea * this.Length;
        }
    }
  28. On the main menu, click Window -> Form1.cs [Design]
  29. Design the form as follows:

    Inheritance With this Object

    Control (Name) Text
    PictureBox  
    Label   Radius:
    TextBox txtRadius
    Label   Length:
    TextBox txtLength
    Button btnCalculate Calculate
    Label   Diameter:
    TextBox txtDiameter
    Label   Circumference:
    TextBox txtCircumference
    Label   Cross Area:
    TextBox txtCrossArea
    Label   Lateral Area:
    TextBox txtLateralArea
    Label Volume:
    TextBox txtVolume
  30. Doble-click the Calculate,button
  31. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry13
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void Present(Cylinder shape)
            {
                txtDiameter.Text      = shape.Diameter.ToString();
                txtCircumference.Text = shape.Circumference.ToString();
                txtCrossArea.Text     = shape.CrossArea.ToString();
                txtLateralArea.Text   = shape.LateralArea.ToString();
                txtVolume.Text        = shape.CentralVolume.ToString();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double radius = 0.00;
                double length = 0.00;
                Cylinder body = new Cylinder();
    
                try
                {
                    radius = Convert.ToDouble(txtRadius.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the radius of the cylinder.", "Geometry - Cylinder");
                }
    
                try
                {
                    length = Convert.ToDouble(txtLength.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the radius of the cylinder.", "Geometry - Cylinder");
                }
    
                body.Radius = radius;
                body.Length = length;
    
                Present(body);
            }
        }
    }
  32. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Inheritance With this Object

  33. In the Radius text box, enter a number such as 79.84
  34. In the Length text box, type a number such as 258.93

    Inheritance With this Object

  35. Click the Calculate button:

    Inheritance With this Object

  36. Close the browser and return to your programming environment
  37. On the main menu, click Project -> Add -> Class...
  38. Change the name of the class as Tank
  39. Click Add
  40. Change the document as follows:
    using static System.Math;
    
    namespace Geometry13
    {
        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 * PI * 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 * PI * 4.00 / 3.00);
                }
            }
        }
    }
  41. Save the following picture somewhere on your computer:

    Geometry - Tank

  42. Click the Form1.cs [Design] tab
  43. Change the Image of the picture box to the saved Tank geometric figure
  44. Change the design of the form as follows:

    Inheritance With this Object

    Control (Name) Text Other Properties
    Label   Radius:  
    TextBox txtRadius    
    Label   ______________________  
    Label   Cylinder Length:  
    TextBox txtLength    
    PictureBox     Image: Tank
    Button btnCalculate Calculate  
    Label   Each Side (Half Sphere): Font: Georgia, 12pt, Italic, Bold, Underline
    Label   Diameter:  
    TextBox txtDiameter    
    Label   Circumference:  
    TextBox txtCircumference    
    Label   Base Area:  
    TextBox txtCrossArea    
    Label   The Central Cylinder Font: Georgia, 12pt, Italic, Bold, Underline
    Label   Lateral Area:  
    TextBox txtLateralArea    
    Label   Central Volume:  
    TextBox txtCentralVolume    
    Label   The Tank as a Whole Font: Georgia, 12pt, Italic, Bold, Underline
    Label   Through Width:  
    TextBox txtWidth    
    Label   Total Length:  
    TextBox txtLateralLength    
    Label   Total Area:  
    TextBox txtTotalArea    
    Label   Total Volume:  
    TextBox txtTotalVolume    
  45. Double-click the Calculate button to access the code
  46. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry13
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void Present(Tank vol)
            {
                txtDiameter.Text      = vol.Diameter.ToString();
                txtCircumference.Text = vol.Circumference.ToString();
                txtCrossArea.Text     = vol.CrossArea.ToString();
                txtLateralArea.Text   = vol.LateralArea.ToString();
                txtCentralVolume.Text = vol.CentralVolume.ToString();
                txtWidth.Text         = vol.Width.ToString();
                txtLateralLength.Text = vol.TotalLength.ToString();
                txtTotalArea.Text     = vol.TotalArea.ToString();
                txtTotalVolume.Text   = vol.TotalVolume.ToString();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double radius = 0.00;
                double length = 0.00;
                Tank whole = new Tank();
    
                try
                {
                    radius = Convert.ToDouble(txtRadius.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the radius of the cylinder.", "Geometric Volume - Tank");
                }
    
                try
                {
                    length = Convert.ToDouble(txtLength.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the radius of the cylinder.", "Geometric Volume - Tank");
                }
    
                whole.Radius = radius;
                whole.Length = length;
    
                Present(whole);
            }
        }
    }
  47. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Displaying a Picture in a Control

  48. In the Radius text box, enter a number such as 79.84
  49. In the Length text box, type a number such as 258.93

    Displaying a Picture in a Control

  50. Click the Calculate button:

    Displaying a Picture in a Control

  51. Close the form and return to your programming environment
  52. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  53. In the list of projects templates, click Windows Forms App (.NET Framework)
  54. Click Next
  55. Change the project Name to Geometry14
  56. Press Enter
  57. In the Solution Explorer, right-click Geometry11 -> Add -> Class...
  58. Change the file name to Circle
  59. 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:

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

Practical LearningPractical Learning: Returning this Object

  1. Change the document as follows:
    using System;
    
    namespace Geometry14
    {
        public class Circle
        {
            public double Radius { get; set; }
    
            public Circle(double radius)
            {
                Radius = radius;
            }
    
            public double Diameter => Radius * 2.00;
            public double Circumference => Diameter * Math.PI;
            public double Area => Radius * Radius * Math.PI;
    
            public Circle Encircle()
        	 {
                return this;
           }
        }
    }
  2. In the Solution Explorer, right-click Geometry11 -> Add -> Class...
  3. Change the name of the class to Cone
  4. Click Add
  5. Change the document as follows:
    using System;
    
    namespace Geometry14
    {
        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 * Math.PI / 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:
    using System;
    
    namespace Geometry14
    {
        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 * Math.PI / 3.00;
    
            public Circle Create()
            {
                return this;
            }
    
            public Cone Surround()
            {
                return this;
            }
        }
    }
  2. Save the following picture somewhere on your computer and return to your programming environment:

    Geometry - Cone

  3. In the Solution Explorer, double-click Form1.cs
  4. Design the form as follows:

    Getting this Parent

    Control (Name) Text Font
    Label   Geometry - Cone Times New Roman, 24pt, Bold
    Label   ______________________  
    PictureBox     Image: Cone.png
    Label   Base Radius::  
    TextBox   txtBaseRadius  
    Label   Height:  
    TextBox txtHeight    
    Button btnCalculate Calculate  
    Label   Base Georgia, 12pt, Bold, Italic, Underline
    Label   Diameter:  
    TextBox txtDiameter    
    Label   Circumference:  
    TextBox txtCircumference    
    Label   Base Area:  
    TextBox txtBaseArea    
    Label   Cone Georgia, 12pt, Bold, Italic, Underline
  5. Double-click the Calculate button
  6. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry14
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double radius = 0.00;
                double height = 0.00;
    
                Cone dongle = new Cone(0.00, 0.00);
                Circle c = dongle.Create();
    
                try
                {
                    radius = Convert.ToDouble(txtBaseRadius.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the radius of the base of the cone.", "Geometric Volume - Cone");
                }
    
                try
                {
                    height = Convert.ToDouble(txtHeight.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the height of the cone.", "Geometric Volume - Cone");
                }
    
                Circle round = new Circle(radius);    
                dongle = new Cone(radius, height);
                
                c = dongle.Create();
    
                txtDiameter.Text = c.Diameter.ToString();
                txtCircumference.Text=c.Circumference.ToString();
                txtBaseArea.Text=c.Area.ToString();
                txtVolume.Text = "0";
            }
        }
    }
  7. To execute the application, press Ctrl + F5:

    Getting this Parent

  8. In the Base Radius text box, type a number such as 84.79
  9. In the Height text box, type a number such as 375.67

    Getting this Parent

  10. Click the Calculate button:

    Getting this Parent

  11. Close the browser and return to your programming environment
  12. Change the code of the Form1.cs as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry14
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double radius = 0.00;
                double height = 0.00;
    
                Cone dongle = new Cone(0.00, 0.00);
                Cone fancy = new Cone(0.00, 0.00);
    
                Circle c = dongle.Create();
    
                try
                {
                    radius = Convert.ToDouble(txtBaseRadius.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the radius of the base of the cone.", "Geometric Volume - Cone");
                }
    
                try
                {
                    height = Convert.ToDouble(txtHeight.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the height of the cone.", "Geometric Volume - Cone");
                }
    
                dongle = new Cone(radius, height);
                fancy = dongle.Surround();
    
                txtDiameter.Text      = fancy.Diameter.ToString();
                txtCircumference.Text = fancy.Circumference.ToString();
                txtBaseArea.Text      = fancy.Area.ToString();
                txtVolume.Text        = fancy.Volume.ToString();
            }
        }
    }
  13. To execute the application to test the form, on the main menu, click Debug -> Start Without Debugging:
  14. In the Base Radius text box, type a number such as 84.79
  15. In the Height text box, type a number such as 375.67
  16. Click the Calculate button:

    Getting this Parent

  17. Close the form and return to your programming environment

Comparing an Object to this Parent

Remember that 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 difference. Consider the following program:

using System;

public class Program
{
    public static void Main()
    {
        Rectangle rect = new Rectangle();

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

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

        return;
    }
}

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

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:

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 this case also, 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:

public class Square
{
    double len;

    public Square(double side)
    {
    }
}

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

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 -> ...Geometry09 project created earlier
  2. Access the TrapezoidalPrism file and add a new method in the class as follows:
    namespace Geometry12
    {
        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 Form1.cs [Design] tab to access the form
  4. Change the design of the form as follows:

    Creating a New Version of a Member of a Class

    Control (Name) Text
    Label   Tota Area:
    TextBox txtTotalArea  
  5. Double-click the Calculate button to access the code of the form
  6. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry09
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            TrapezoidalPrism Prepare()
            {
                double top = 0.00;
                double bottom = 0.00;
                double height = 0.00;
                double length = 0.00;
    
                try
                {
                    top = double.Parse(txtTopBase.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the top base", "Geometry");
                }
    
                try { bottom = double.Parse(txtBottomBase.Text); }
                catch (FormatException)
                {
                    MessageBox.Show("The value you specified for the bottom base is not valie", "Geometry");
                }
    
                try
                {
                    height = double.Parse(txtHeight.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Either you didn't provide a value for the height or you left it empty.", "Geometry");
                }
    
                try
                {
                    length = double.Parse(txtLength.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Please make sure you enter an appropriate value for the length.", "Geometry");
                }
    
                return new TrapezoidalPrism(top, bottom, height, length);
    
            }
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                TrapezoidalPrism tp = Prepare();
    
                Present(tp);
            }
    
            void Present(TrapezoidalPrism shape)
            {
                txtBaseArea.Text   = shape.BaseArea.ToString();
                txtTopArea.Text    = shape.TopArea.ToString();
                txtBottomArea.Text = shape.BottomArea.ToString();
                txtTotalArea.Text  = shape.Area.ToString();
                txtVolume.Text     = shape.Volume.ToString();
            }
        }
    }
  7. To execute the application, on the menu, click Debug -> Start Without Debugging:

    Creating a New Version of a Member of a Class

  8. In the Top Base text box, enter a number such as 137.96
  9. In the Bottom Base text box, enter a number such as 209.73
  10. In the Height text box, enter a number such as 87.59
  11. In the Length text box, enter a number such as 142.46

    Creating a New Version of a Member

  12. Click the Calculate button:

    Creating a New Version of a Member

  13. Close the form and return to your programming environment
  14. Close your programming environment

Previous Copyright © 2001-2021, FunctionX Next