A Class from a Class

Introduction

Inheritance consists of creating a class that is derived from another class. Here is an example:

namespace Exercises.Models
{
    public class Circle
    {
    }

    public class Cylinder : Circle
    {

    }
}

After starting a class, you can add members to it. For example, you can declare a variable in a class. You can create a field in a class. Here is an example:

namespace Exercises.Models
{
    public class Circle
    {

    }

    public class Cylinder : Circle
    {
        private string purpose;
    }
}

The Protected Members of a Class

To indicate that a member can be accessed only in a class or by members of a derived class, mark the member with the protected keyword. Here is an example of a protected field:

@functions{
    internal class Circle
    {
        protected double radius;
    }
}

@functions{
    public class Cylinder : Circle
    {
        public double Height { get; set; }

        public Cylinder(double baseRadius = 0.00, double height = 0.00)
        {
            radius = baseRadius;
            Height = height;
        }

        public double LateralArea
        {
            get
            {
                return Circumferemce * Height;
            }
        }

        public double Volume
        {
            get
            {
                return Area * Height;
            }
	    }
    }
}

Introduction to Built-In Classes

Overview

You can create some of the classes you need for your applications, but to assist you, the .NET Framework provides many built-in classes you can use.

Introduction to the Object

To support objects, the .NET Framework provides the Object class represented in the C# language by the object data type. You can use that type to declare a variable of any kind. After declaring the variable, initialize it with a value of your choice. Here are examples:

@{
    // An object variable for a string
    object employeeName = "Philippe Blayne";
    // An object variable for an integer
    object yearsOfExperience = 5;
    // An object variable for a decimal number
    object hourlySalary = 26.95;
}

To present the value to the user, you can include its variable in an HTML tag. Here are examples:

@page
@model Valuable.Pages.FoundationsModel
@{
    object employeeName = "Philippe Blayne";
    object hourlySalary = 26.95;
    object yearsOfExperience = 5;
}

<h3>=//= Employee Record =//=</h3>
<b>Employee Name:</b> @employeeName</p>
<b>Hourly Salary:</b> @hourlySalary</p>
<p><b>Length of Experience:</b> @yearsOfExperience years</p>

This would produce:

=//= Employee Record =//=
Employee Name: Philippe Blayne
Hourly Salary: 26.95
Length of Experience: 5 years
Press any key to continue . . .

You can also use object as a type for a parameter to a method or a function. Here are examples:

@{
    void PresentEmployeeSummary(object something)
    {

    }

    void Present(object name, int category)
    {

    }

    void Summarize(object message, int @class, object status)
    {

    }
}

Creating an Object-Based Class

Because Object is the most fundamental class in .NET, if you create a class, that class is implicitly derived from Object. Still, you can indicate this inheritance in a class you are creating. Here is an example:

@functions{
    public class Person : Object
    {
    
    }
}

Random Numbers

To support random numbers, the .NET Framework provides the Random class. You can use it to generate random numbers as the class is equipped with two constructors and the Next() method. Here are examples:

@page
@model Valuable.Pages.FoundationsModel

@{
    Random rand = new Random();

    int rndNumber1 = rand.Next();
    int rndNumber2 = rand.Next();
    int rndNumber3 = rand.Next(100);
    int rndNumber4 = rand.Next(100);
    int rndNumber5 = rand.Next(6, 18);
    int rndNumber6 = rand.Next(6, 18);
}

<pre>Random Number: @rndNumber1
Random Number: @rndNumber2
Random Number: @rndNumber3
Random Number: @rndNumber4
Random Number: @rndNumber5
Random Number: @rndNumber6</pre>

Here is an example of what this could produce:

Random Number: 12
Random Number: 14
Random Number: 11
Random Number: 83
Random Number: 7
Random Number: 12

Exception Handling

Introduction

An exception is an unusual situation in an application. The ability to deal with exceptions in an application is called exception handling. Exception handling is primarily done with the try and the catch keywords. Here is an example:

@page
@model PracticalLearning.Pages.ExceptionHandlingModel
@{
    string strMessage = "";
    double number = 0.00, result = 0.00;

    if (Request.HasFormContentType)
    {
        try
        {
            number = double.Parse(Request.Form["txtNumber"]);
            result = number * 2.00;
        }
        catch
        {
            strMessage = "The value you entered is not a valid number.";
        }
    }
}

<form method="post" name="frmNumbers">
    <table style="width: 300px" align="center">
        <tr>
            <td style="width: 150px">Number:</td>
            <td><input type="text" id="txtNumber" value="@number" style="width: 345px" /></td>
        </tr>
    </table>

    <table style="width: 300px" align="center">
        <tr>
            <td style="width: 50px">&nbsp;</td>
            <td><input type="submit" value="Add" name="btnCalculate" style="width: 150px" /></td>
        </tr>
    </table>

    <table style="width: 300px" align="center">
        <tr>
            <td style="width: 150px">Result:</td>
            <td><input type="text" id="txtResult" value="@result" style="width: 100px" /> %</td>
        </tr>
    </table>
</form>

Exceptions in the .NET Framework

To support exception handling, the .NET Framework provides many classes. The most fundamental class for exceptions is named Exception. There exist many other classes, such as FormatException, OverflowException, ArgumentOutOfRangeException, DivideByZeroException, etc.

Practical LearningPractical Learning: Handling an Exception

  1. Change the Index.cshtml code as follows:
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    @{
        /* New York State and New York City 
         * https://www.tax.ny.gov/pdf/current_forms/it/it2105i.pdf */
        string? strMessage = null;
        string strNetPay = "0.00";
        string strTaxAmount = "0.00";
        double taxRateExcess = 0.00;
        double amountInExcess = 0.00;
        string strGrossSalary = "0.00";
    
        if (Request.HasFormContentType)
        {
            double excess;
            double taxAmount = 0.00;
            double grossSalary = 0.00;
    
            try
            {
                grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
    
                // Married Filing Jointly and Qualifying Widow(er)
                if (grossSalary is (>= 0.00) and (<= 17_150))
                {
                    taxRateExcess = 4.00;
                    amountInExcess = 0.00;
                    taxAmount = grossSalary * 4.00 / 100.00;
                }
                else if (grossSalary is (> 17_150) and (<= 23_600))
                {
                    taxRateExcess = 4.50;
                    amountInExcess = 686;
                    excess = (grossSalary - 17_150) * 4.5 / 100.00;
                    taxAmount = excess + 686;
                }
                else if (grossSalary is (> 23_600) and (<= 27_900))
                {
                    taxRateExcess = 5.25;
                    amountInExcess = 976;
                    excess = (grossSalary - 23_600) * 5.25 / 100.00;
                    taxAmount = excess + 976;
                }
                else if (grossSalary is (> 27_900) and (<= 161_550))
                {
                    taxRateExcess = 5.85;
                    amountInExcess = 1_202;
                    excess = (grossSalary - 27_900) * 5.85 / 100.00;
                    taxAmount = excess + 1_202;
                }
                else if (grossSalary is (> 161_550) and (<= 323_200))
                {
                    taxRateExcess = 6.25;
                    amountInExcess = 9_021;
                    excess = (grossSalary - 161_550) * 6.25 / 100.00;
                    taxAmount = excess + 9_021;
                }
                else if (grossSalary is (> 323_200) and (<= 2_155_350))
                {
                    taxRateExcess = 6.85;
                    amountInExcess = 19_124;
                    excess = (grossSalary - 323_200) * 6.85 / 100.00;
                    taxAmount = excess + 19_124;
                }
                else if (grossSalary is (> 2_155_350) and (<= 5_000_000))
                {
                    taxRateExcess = 9.65;
                    amountInExcess = 144_626;
                    excess = (grossSalary - 2_155_350) * 9.65 / 100.00;
                    taxAmount = excess + 144_626;
                }
                else if (grossSalary is (> 5_000_000) and (<= 25_000_000))
                {
                    taxRateExcess = 10.3;
                    amountInExcess = 419_135;
                    excess = (grossSalary - 5_000_000) * 10.3 / 100.00;
                    taxAmount = excess + 419_135;
                }
                else // if(grossSalary is > 25_000_000)
                {
                    taxRateExcess = 10.9;
                    amountInExcess = 2_479_135;
                    excess = (grossSalary - 25_000_000) * 10.9 / 100.00;
                    taxAmount = excess + 2_479_135;
                }
            }
            catch (FormatException fexc)
            {
                strMessage = "It appears that you didn't provide a valid value for the gross salary. The message produced is " +
                             System.Environment.NewLine + fexc.Message;
            }
    
            strGrossSalary = $"{grossSalary:F}";
            strTaxAmount = $"{taxAmount:F}";
            strNetPay = $"{(grossSalary - taxAmount):F}";
        }
    }
    
    <h1 class="text-center common-font">- DeltaX - Tax Preparation Services -</h1>
    <hr />
    <h2 class="text-center common-font">- New York State - State Income Tax -</h2>
    <hr />
    <div class="delimiter common-font">
        <form name="frmTaxPreparation" method="post">
            <table class="table common-font">
                <tr>
                    <td width="150">@Html.Label("txtGrossSalary", "Gross Salary:", new { @class = "" })</td>
                    <td>@Html.TextBox("txtGrossSalary", @strGrossSalary, new { @class = "form-control" })</td>
                </tr>
                <tr>
                    <td></td>
                    <td class="pcenter"><input type="submit" value="Evaluate Taxes" class="btn-primary" /></td>
                </tr>
            </table>
        </form>
        
        <table class="table">
            <tr>
                <td width="250">Gross Salary:</td>
                <td>@strGrossSalary</td>
            </tr>
            <tr>
                <td>Tax Rate in Excess:</td>
                <td>@taxRateExcess%</td>
            </tr>
            <tr>
                <td>Amount Added in Excess:</td>
                <td>@amountInExcess</td>
            </tr>
            <tr>
                <td>Tax Amount from Income:</td>
                <td>@strTaxAmount</td>
            </tr>
            <tr>
                <td>Net Pay:</td>
                <td>@strNetPay</td>
            </tr>
        </table>
    
        <p>@strMessage</p>
    </div>
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. If the browser presents a Resend button, click it. Otherwise, refresh the browser
  4. Delete the value in the Gross Salary text box and click the Evaluate Taxes button:

    Introduction to Exception Handling

  5. Change the Gross Salary to 26197.53 and click the Evaluate Taxes button:

    Introduction to Exception Handling

  6. Return to your programming environment

Throwing an Exception

To indicate that you want to issue an exception you are anticipating in your code, use the throw keyword, followed by the new operator and an Exception-based class.

Catching Various Exceptions

You can write code that deals with various exceptions. To do this, after the try clause, create a catch() section for each exception. Enter the desired exception argument in a catch() clause.

Nesting an Exception

You can nest an exception inside another exception.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2023, C# Key Monday 27 December 2021 Next