Introduction

When you are creating a class, if you anticipate that a certain member should be redefined in a derived class, you can indicate this in your code. On the other hand, while creating a class that is based on another, if you find out that you are customizing a member that already exists in the base class, you should indicate, in your code, that you are providing a new version. In both cases, the common member is said to be a virtual member of the class.

Practical LearningPractical Learning: Introcing Abstraction

  1. Save the following picture somewhere on your computer and return to your programming environment:

    Geometry - Square

  2. Start Microsoft Visual Studio
  3. On the main menu, click File -> New -> Project...
  4. In the middle list, click ASP.NET Web Application (.NET Framework) and, in the Name text box, replace the name with Geometry12
  5. Click OK
  6. In the New ASP.NET Web Application dialog box, make sure Empty is hilighted and click OK
  7. In the Solution Explorer, right-click Geometry12 -> Add -> Folder
  8. Type Images and press Enter
  9. Add the above picture to the images folder
  10. In the Solution Explorer, right-click Geometry12, position the mouse on Add, position the mouse on Add ASP.NET Folder, and click App_Code
  11. In the Solution Explorer, right-click App_Code -> Add -> Class...
  12. Change the file name to Square
  13. Click Add
  14. Change the document as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Geometry12.App_Code
    {
        public class Square
        {
            public double Side { get; set; }
    
            public Square(double side)
            {
                Side = side;
            }
    
            public double Perimeter
            {
                get
                {
                    return Side * 4.00;
                }
            }
        }
    }

Virtual Methods

A method is said to be virtual if it is anticipated to have different versions or implementations in classes that derive from it. To create a virtual method, in the base class, type the virtual keyword to the left of the return type of the method. If the method has an access level (private, public, or internal), the virtual keyword can appear before or after the access level.

Practical LearningPractical Learning: Creating Virtual Methods

Virtual Properties

A property of a class is virtual if it may be implemented in a derived class. This means that the property should primarily be created in its original class.

To get a virtual property, when creating the class, add the virtual keyword before the return type of the property.

Practical LearningPractical Learning: Creating a Virtual Property

  1. Create a virtual property in the Square class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Geometry12.App_Code
    {
        public class Square
        {
            public double Side { get; set; }
    
            public Square(double side)
            {
                Side = side;
            }
    
            public double Perimeter
            {
                get
                {
                    return Side * 4.00;
                }
            }
    
            public virtual double Area
            {
                get
                {
                    return Side * Side;
                }
            }
            
            public virtual double CalculateInradius()
            {
                return Side / 2.00;
            }
    
            public virtual double CalculateCircumradius()
            {
                return Math.Sqrt(2.00) * Side / 2.00;
            }
        }
    }
  2. In the Solution Explorer, right-click the name of the project -> Add -> New Item...
  3. In the left list, expand Web, and click Razor
  4. In the middle list, click Web Page (Razor)
  5. Change the name to Index
  6. Press Enter
  7. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .container {
        margin: auto;
        width: 550px;
    }
    
    .col-empty {
        width: 40px
    }
    
    .col-format {
        width: 120px
    }
    </style>
    <title>Geometry - Square</title>
    </head>
    <body>
    <h2 style="text-align: center">Geometry - Square</h2>
    <p style="text-align: center"><img src="~/Images/Square.png" alt="Geometry - Square" width="483" height="305" /></p>
    
    @{ 
        double side = 0.00;
        Geometry12.App_Code.Square sqr = new Geometry12.App_Code.Square(0.00);
    
        if (IsPost)
        {
            side = Convert.ToDouble(Request["txtSide"]);
            sqr = new Geometry12.App_Code.Square(side);
        }
    }
    <div class="container">
        <form name="frmGeometry" method="post">
            <table>
                <tr>
                    <td style="width: 80px">Side:</td>
                    <td><input type="text" name="txtSide" style="width: 60px" value="@side" /></td>
                    <td><input type="submit" name="btnCalculate" value="Calculate" /></td>
                    <td>Perimter:</td>
                    <td><input type="text" name="txtPerimter" value="@sqr.Perimeter" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>Area:</td>
                    <td><input type="text" name="txtArea" value="@sqr.Area" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>Inscribed Radius:</td>
                    <td><input type="text" name="txtInscribedRadius" value="@sqr.CalculateInradius()" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>Circumscribed Radius:</td>
                    <td><input type="text" name="txtCircumscribedRadius" value="@sqr.CalculateCircumradius()" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  8. To execute the application to test the webpage, press Ctrl + F5:

    Creating and Using Virtual Members

  9. In the Side text box, type a number such as 429.63:

    Creating and Using Virtual Members

  10. Click the Calculate button:

    Creating and Using Virtual Members

  11. Close the browser and return to your programming environment
  12. Save the following picture somewhere on your computer and return to your programming environment:

    Creating a Virtual Method

  13. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  14. In the middle list, click ASP.NET Web Application (.NET Framework) and, in the Name text box, replace the name with Geometry13
  15. Click OK
  16. In the New ASP.NET Web Application dialog box, click Empty and click OK
  17. In the Solution Explorer, right-click Geometry13, position the mouse on Add, position the mouse on Add ASP.NET Folder, and click App_Code
  18. In the Solution Explorer, right-click Geometry13 -> Add -> Folder
  19. Type Images and press Enter
  20. Add the above picture to the images folder
  21. In the Solution Explorer, right-click App_Code -> Add -> Class...
  22. Change the name of the file to Trapezoid
  23. Click Add
  24. Change the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Geometry13.App_Code
    {
        public class Trapezoid
        {
            public double ShortSide { get; set; }
            public double LongSide { get; set; }
            public double Edge { get; set; }
    
            public Trapezoid(double sSide, double lSide, double edge)
            {
                ShortSide = sSide;
                LongSide  = lSide;
                Edge      = edge;
            }
    
            public double Perimeter => LongSide + Edge + ShortSide + Edge;
    
            // http://mathworld.wolfram.com/IsoscelesTrapezoid.html
            public double Height
            {
                get
                {
                    return Math.Sqrt((Edge * Edge) - (Math.Pow(LongSide - ShortSide, 2.00) / 4.00));
                }
            }
    
            virtual public double CalculateArea()
            {
                return (LongSide + ShortSide) * Height / 2.00;
            }
        }
    }
  25. In the Solution Explorer, right-click the name of the project -> Add -> New Item...
  26. In the left list, expand Web, and click Razor
  27. In the middle list, click Web Page (Razor)
  28. Change the name to Index
  29. Press Enter
  30. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Geometry - Trapezoid</title>
    <style>
    .container {
        margin: auto;
        width: 620px;
    }
    </style>
    </head>
    <body>
    @{
        double shortSide = 0.00;
        double longSide  = 0.00;
        double border = 0.00;
        Geometry13.App_Code.Trapezoid trap = new Geometry13.App_Code.Trapezoid(sSide : 0.00, lSide : 0.00, edge : 0.00);
    
        if (IsPost)
        {
            shortSide = Convert.ToDouble(Request["txtShortSide"]);
            longSide  = Convert.ToDouble(Request["txtLongSide"]);
            border    = Convert.ToDouble(Request["txtEdge"]);
    
            trap = new Geometry13.App_Code.Trapezoid(sSide : shortSide, lSide : longSide, edge: 0.00);
        }
    }
    
    <div class="container">
        <h2 style="text-align: center">Geometry - Trapezoid</h2>
    
        <form name="frmGeometry" method="post">
                <table>
                    <tr>
                        <td style="width: 375px" rowspan="9">
                            <img src="~/images/trapezoid2.png" width="373" height="273" alt="Geometry - Trapezoid">
                        </td>
                        <td style="width: 150px">Short Side:</td>
                        <td><input type="text" name="txtShortSide" value="@shortSide" /></td>
                    </tr>
                    <tr>
                        <td>Long Side:</td>
                        <td><input type="text" name="txtLongSide" value="@longSide" /></td>
                    </tr>
                    <tr>
                        <td>Edge:</td>
                        <td><input type="text" name="txtEdge" value="@border" /></td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td style="text-align: center"><input type="submit" name="btnSubmit" value="Calculate" /></td>
                    </tr>
                    <tr>
                        <td>Height:</td>
                        <td><input type="text" name="txtHeight" value="et.Height" /></td>
                    </tr>
                    <tr>
                        <td>Perimeter:</td>
                        <td><input type="text" name="txtPerimeter" value="et.Inradius" /></td>
                    </tr>
                    <tr>
                        <td>Area:</td>
                        <td><input type="text" name="txtArea" value="et.Area" /></td>
                    </tr>
                </table>
        </form>
    </div>
    </body>
    </html>
  31. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Displaying a Picture in a Control

  32. In the Short Side text box, enter a number such as 137.96
  33. In the Long Side text box, enter a number such as 209.73
  34. In the Edge text box, enter a number such as 87.59

    Displaying a Picture in a Control

  35. Click the Calculate button:

    Displaying a Picture in a Control

  36. Close the browser and return to your programming environment
  37. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  38. Make sure ASP.NET Web Application (.NET Framework) is selected in the middle list and, in the Name text box, replace the name with Geometry14
  39. Click OK
  40. In the New ASP.NET Web Application dialog box, make sure Empty is selected and press Enter
  41. In the Solution Explorer, right-click the name of the project -> Add -> Add ASP.NET Folder -> App_Code
  42. In the Solution Explorer, right-click the name of the project -> Add -> Folder
  43. Type Images and press Enter
  44. Add the tp.png picture from the previous lesson to the images folder of this project
  45. In the Solution Explorer, right-click App_Code -> Add -> Class...
  46. Change the name of the file to Trapezoid
  47. Click Add
  48. Fill the class as follows:
  49. On the main menu, click Project -> Add Class...
  50. Set the name of the class as Trapezoid and click Add
  51. Fill the class as follows:
    using static System.Math;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Geometry14.App_Code
    {
        public class Trapezoid
        {
            public double ShortSide { get; set; }
            public double LongSide { get; set; }
            public double Edge { get; set; }
    
            public Trapezoid(double sSide, double lSide, double side)
            {
                ShortSide = sSide;
                LongSide = lSide;
                Edge = side;
            }
    
            public double Perimeter => LongSide + Edge + ShortSide + Edge;
    
            // http://mathworld.wolfram.com/IsoscelesTrapezoid.html
            public double Height
            {
                get
                {
                    return Sqrt((Edge * Edge) - (Pow(LongSide - ShortSide, 2.00) / 4.00));
                }
            }
    
            virtual public double CalculateArea()
            {
                return (LongSide + ShortSide) * Height / 2.00;
            }
        }
    }
  52. In the Solution Explorer, right-click App_Code -> Add -> Class...
  53. Set the name of the class as TrapezoidalPrism
  54. Click Add
  55. Change the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Geometry14.App_Code
    {
        public class TrapezoidalPrism : Trapezoid
        {
            public double Length { get; set; }
    
            public TrapezoidalPrism(double sSide, double lSide, double side, double len)
                : base(sSide, lSide, side)
            {
                Length = len;
            }
    
            public double BaseArea => base.CalculateArea();
    
            public double Volume => BaseArea * Length;
        }
    }

Overriding a Member in a Derived Class

As seen in previous sections, you can create a virtual method or property in a class and use it like any other method or property of its class. As mentioned in our introduction, the essence of creating a virtual method or property to provide a different implementation of that member in its own and in classes that derive from that class. Providing a different version of a member or property in a derived class is referred to as overriding the method or property.

To override a method, in a derived class, create a method with the same syntax (same return type, same name, and same parameter(s) if any) as the method in the parent class. This time, replace the virtual keyword with the override keyword. In the same way, to override a propertty, create one of the same return type and name in the derived class but use the override keyword instead of the the virtual keyword.

Practical LearningPractical Learning: Overriding a Method in a Derived Class

  1. In the TrapezoidalPrism class, override the CalculateArea() method as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Geometry14.App_Code
    {
        public class TrapezoidalPrism : Trapezoid
        {
            public double Length { get; set; }
    
            public TrapezoidalPrism(double sSide, double lSide, double side, double len)
                : base(sSide, lSide, side)
            {
                Length = len;
            }
    
            public double BaseArea => base.CalculateArea();
    
            override public double CalculateArea()
            {
                double shortArea = ShortSide * Length;
                double longArea = LongSide * Length;
                double sideArea = Edge * Length;
                return (BaseArea * 2.00) + shortArea + longArea + (sideArea * 2.00);
            }
    
            public double Volume => BaseArea * Length;
        }
    }
  2. In the Solution Explorer, right-click the name of the project -> Add -> New Item...
  3. In the left list, expand Web, and click Razor
  4. In the middle list, click Web Page (Razor)
  5. Change the name to Index
  6. Press Enter
  7. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .container {
        margin: auto;
        width: 650px;
    }
    </style>
    <title>Geometry - Trapezoidal Prism</title>
    </head>
    <body>
    @{
        double shortSide = 0.00;
        double longSide = 0.00;
        double edge = 0.00;
        double length = 0.00;
    
        Geometry14.App_Code.TrapezoidalPrism tp = new Geometry14.App_Code.TrapezoidalPrism(shortSide, longSide, edge, length);
    
        if (IsPost)
        {
            shortSide = Convert.ToDouble(Request["txtShortSide"]);
            longSide = Convert.ToDouble(Request["txtLongSide"]);
            edge = Convert.ToDouble(Request["txtEdge"]);
            length = Convert.ToDouble(Request["txtLength"]);
    
            tp = new Geometry14.App_Code.TrapezoidalPrism(shortSide, longSide, edge, length);
        }
    }
    
    <div class="container">
        <h2 style="text-align: center">Geometry - Trapezoid</h2>
    
        <form name="frmGeometry" method="post">
            <table>
                <tr>
                    <td>
                        <img src="~/images/tp.png" width="373" height="273" alt="Geometry - Trapezoid"></td>
                    <td>
                        <p>Base</p>
                        <table>
                            <tr>
                                <td style="width: 20px">&nbsp;</td>
                                <td style="width: 120px">Short Side:</td>
                                <td><input type="text" name="txtShortSide" value="@shortSide" /></td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td>Long Side:</td>
                                <td><input type="text" name="txtLongSide" value="@longSide" /></td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td>Edge:</td>
                                <td><input type="text" name="txtEdge" value="@edge" /></td>
                            </tr>
                        </table>
                        <p>Prism</p>
                        <table>
                            <tr>
                                <td style="width: 20px">&nbsp;</td>
                                <td style="width: 120px">Length:</td>
                                <td><input type="text" name="txtLength" value="@length" /></td>
                            </tr>
                        </table>
    
                        <p style="text-align: center"><input type="submit" name="btnSubmit" value="Calculate" /></p>
    
                        <p>Base</p>
    
                        <table>
                            <tr>
                                <td style="width: 20px">&nbsp;</td>
                                <td style="width: 120px">Height:</td>
                                <td><input type="text" name="txtHeight" value="@tp.Height" /></td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td>Perimeter:</td>
                                <td><input type="text" name="txtPerimeter" value="@tp.Perimeter" /></td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td>Base Area:</td>
                                <td><input type="text" name="txtBaseArea" value="@tp.BaseArea" /></td>
                            </tr>
                        </table>
    
                        <p>Prism</p>
    
                        <table>
                            <tr>
                                <td style="width: 20px">&nbsp;</td>
                                <td style="width: 120px">Total Area:</td>
                                <td><input type="text" name="txt>TotalArea" value="@tp.CalculateArea()" /></td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td>Volume:</td>
                                <td><input type="text" name="txtVolume" value="@tp.Volume" /></td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  8. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Overriding a Method in a Derived Class

  9. In the Short Side text box, enter a number such as 229.47
  10. In the Long Side text box, enter a number such as 167.66
  11. In the Edge text box, enter a number such as 98.59
  12. In the Length text box, enter a number such as 214.85

    Overriding a Method in a Derived Class

  13. Click the Calculate button:

    Overriding a Method in a Derived Class

  14. Close the browser and return to your programming environment
  15. Close your programming environment

Previous Copyright © 2002-2019, FunctionX Next