Variants of an else Conditional Statements

The Ternary Operator (?:)

If you have a condition that can be checked as an if situation with one alternate else, you can use the ternary operator that is a combination of ? and :. Its formula is:

condition ? statement1 : statement2;

The condition would first be checked. If the condition is true, then statement1 would execute. If not, statement2 would execute.

Practical LearningPractical Learning: Using the Ternary Operator

  1. Start Microsoft Visual Studio
  2. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  3. In the middle list, click ASP.NET Application (.NET Framework) and change the project Name to PayrollPreparation06
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, click Empty and press Enter
  6. In the Solution Explorer, right-click PayrollPreparation06 -> Add -> New Folder
  7. Type Content and press Enter
  8. In the Solution Explorer, right-click Content -> Add -> New Item...
  9. In the Add New Item dialog box, in the left list, click Web and, in the middle list, click Style Sheet
  10. Change the file Name to Site
  11. Press Enter
  12. Change the code as follows:
    .container {
        margin: auto;
        width: 600px;
    }
    .tbl-formatting  { width:      100%;   }
    .centering       { text-align: center; }
    .ctrl-formatting { width:      80px;   }
  13. In the Solution Explorer, right-click PayrollPreparation06 -> Add -> Add ASP.NET Folder -> App_Code
  14. In the Solution Explorer, right-click App_Code -> Add -> Class...
  15. Change the name to TimeSheet
  16. Press Enter
  17. Change the code as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace PayrollPreparation06.App_Code
    {
        public class TimeSheet
        {
            public double Monday { get; set; }
            public double Tuesday { get; set; }
            public double Wednesday { get; set; }
            public double Thursday { get; set; }
            public double Friday { get; set; }
    
            public TimeSheet()
            {
                Monday = 0.00;
                Tuesday = 0.00;
                Wednesday = 0.00;
                Thursday = 0.00;
                Friday = 0.00;
            }
    
            public TimeSheet(double mon, double tue,
                             double wed, double thu, double fri)
            {
                Monday = mon;
                Tuesday = tue;
                Wednesday = wed;
                Thursday = thu;
                Friday = fri;
            }
    
            public double MondayOvertime
            {
                get
                {
                    return (Monday <= 8.00) ? 0.00 : (Monday - 8.00);
                }
            }
            public double TuesdayOvertime
            {
                get
                {
                    return (Tuesday <= 8.00) ? 0.00 : (Tuesday - 8.00);
                }
            }
            public double WednesdayOvertime
            {
                get
                {
                    return (Wednesday <= 8.00) ? 0.00 : (Wednesday - 8.00);
                }
            }
            public double ThursdayOvertime
            {
                get
                {
                    return (Thursday <= 8.00) ? 0.00 : (Thursday - 8.00);
                }
            }
            public double FridayOvertime
            {
                get
                {
                    return (Friday <= 8.00) ? 0.00 : (Friday - 8.00);
                }
            }
        }
    }
  18. In the Solution Explorer, click PayrollPreparation06 to select it
  19. On the main menu, click Project -> Add New Item...
  20. In the left list, expand Web and click Razor
  21. In the middle list, click Web Page (Razor v3)
  22. Change the name to Index
  23. Click Add
  24. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    <title>Fun Department Store - Payroll Preparation</title>
    </head>
    <body>
    <div class="container">
        <h2 class="centering">Fun Department Store</h2>
        <h3 class="centering">Payroll Preparation</h3>
    </div>
    
    @{
        string strMondayOvertime = "0.00";
        string strTuesdayOvertime = "0.00";
        string strFridayOvertime = "0.00";
        string strWednesdayOvertime = "0.00";
        string strThursdayOvertime = "0.00";
    
        PayrollPreparation06.App_Code.TimeSheet ts = new PayrollPreparation06.App_Code.TimeSheet();
    
        if (IsPost)
        {
            double mon = Convert.ToDouble(Request["txtMonday"]);
            double tue = Convert.ToDouble(Request["txtTuesday"]);
            double wed = Convert.ToDouble(Request["txtWednesday"]);
            double thu = Convert.ToDouble(Request["txtThursday"]);
            double fri = Convert.ToDouble(Request["txtFriday"]);
    
            ts = new PayrollPreparation06.App_Code.TimeSheet(mon, tue, wed, thu, fri);
    
            strMondayOvertime = ts.MondayOvertime.ToString("F");
            strTuesdayOvertime = ts.TuesdayOvertime.ToString("F");
            strWednesdayOvertime = ts.WednesdayOvertime.ToString("F");
            strThursdayOvertime = ts.ThursdayOvertime.ToString("F");
            strFridayOvertime = ts.FridayOvertime.ToString("F");
        }
    }
    
    <div class="container">
        <form name="frmPayrollPreparation" method="post">
            <table class="tbl-formatting">
                <tr>
                    <td>&nbsp;</td>
                    <td>Monday</td>
                    <td>Tuesday</td>
                    <td>Wednesday</td>
                    <td>Thursday</td>
                    <td>Friday</td>
                </tr>
                <tr>
                    <td>Time Workd:</td>
                    <td><input type="text" name="txtMonday" class="ctrl-formatting" value="@ts.Monday" /></td>
                    <td><input type="text" name="txtTuesday" class="ctrl-formatting" value="@ts.Tuesday" /></td>
                    <td><input type="text" name="txtWednesday" class="ctrl-formatting" value="@ts.Wednesday" /></td>
                    <td><input type="text" name="txtThursday" class="ctrl-formatting" value="@ts.Thursday" /></td>
                    <td><input type="text" name="txtFriday" class="ctrl-formatting " value="@ts.Friday" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td colspan="5" style="text-align: center; height: 32px;"><input type="submit" name="btnCalculate" style="width: 300px" value="Calculate" /></td>
                </tr>
                <tr>
                    <td>Overtimes:</td>
                    <td><input type="text" name="txtMondayOvertime" class="ctrl-formatting " value="@strMondayOvertime" /></td>
                    <td><input type="text" name="txtTuesdayOvertime" class="ctrl-formatting" value="@strTuesdayOvertime" /></td>
                    <td><input type="text" name="txtWednesdayOvertime" class="ctrl-formatting" value="@strWednesdayOvertime" /></td>
                    <td><input type="text" name="txtThursdayOvertime" class="ctrl-formatting" value="@strThursdayOvertime" /></td>
                    <td><input type="text" name="txtFridayOvertime" class="ctrl-formatting" value="@strFridayOvertime" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  25. To execute the project, press Ctrl + F5

    Finding Out Whether a Value is Greater Than Another Value

  26. In each day's text box, type a decimal number between 0 and 16 but divisible by 0.50. Here are examples:

    Finding Out Whether a Value is Greater Than Another Value

  27. Click the Calculate button:

    Finding Out Whether a Value is Greater Than Another Value

  28. Close the browser and return to your programming environment
  29. To create body-less properties, access the TimeSheet.cs file and change the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace PayrollPreparation06.App_Code
    {
        public class TimeSheet
        {
            public double Monday { get; set; }
            public double Tuesday { get; set; }
            public double Wednesday { get; set; }
            public double Thursday { get; set; }
            public double Friday { get; set; }
    
            public TimeSheet()
            {
                Monday = 0.00;
                Tuesday = 0.00;
                Wednesday = 0.00;
                Thursday = 0.00;
                Friday = 0.00;
            }
    
            public TimeSheet(double mon, double tue,
                             double wed, double thu, double fri)
            {
                Monday = mon;
                Tuesday = tue;
                Wednesday = wed;
                Thursday = thu;
                Friday = fri;
            }
    
            public double MondayOvertime    => (Monday    <= 8.00) ? 0.00 : (Monday    - 8.00);
            public double TuesdayOvertime   => (Tuesday   <= 8.00) ? 0.00 : (Tuesday   - 8.00);
            public double WednesdayOvertime => (Wednesday <= 8.00) ? 0.00 : (Wednesday - 8.00);
            public double ThursdayOvertime  => (Thursday  <= 8.00) ? 0.00 : (Thursday  - 8.00);
            public double FridayOvertime    => (Friday    <= 8.00) ? 0.00 : (Friday    - 8.00);
        }
    }
  30. On the Standard toolbar, click the Save button Save

if...else if and if...else

If you use an if...else situation, you can process only two statements. In some cases, you may deal with more than two conditions. In this case, you can use an if...else if condition. Its formula is:

if(condition1) statement1;
else if(condition2) statement2;

If you writing your code in a webpage, the statements must be delimited by curly brackets. Therefore, they would use the following formulas:

if(condition1) {
    statement1;
}
else if(condition2) {
    statement2;
}

The first condition, condition1, would first be checked. If condition1 is true, then statement1 would execute. If condition1 is false, then condition2 would be checked. If condition2 is true, then statement2 would execute. Any other result would be ignored.

Because there can be other alternatives, the C# language provides an alternate else condition as the last resort. Its formula is:

if(condition1)
    statement1;
else if(condition2)
    statement2;
else
    statement-n;

If you are writing the code in a web page, each statement must be enclosed in curly brackets. The formula to use is:

if(condition1){
    statement1;
}
else if(condition2) {
    statement2;
}
else {
    statement-n;
}

if...else if ... else if and else

The if...else conditional statement allows you to process many conditions. The formula to follow is:

if(condition1) statement1;
else if(condition2) statement2;
. . .
else if(condition_n) statement_n;

If you are writing the code in a webpage, each statement must be included in curly brackets. The formula to follow is:

if(condition1) { statement1; }
else if(condition2) { statement2; }
. . .
else if(condition_n) { statement_n; }

The conditions would be checked from the beginning one after another. If a condition is true, then its corresponding statement would execute.

If there is a possibility that none of the conditions would respond true, you can add a last else condition and its statetement. The formula to follow is:

if(condition1)
    statement1;
else if(condition2)
    statement2;
. . .
else if(condition_n)
    statement_n;
else
    statement-n;

In a webpage, the formula to follow is:

if(condition1) {
    statement1;
}
else if(condition2) {
    statement2;
}
. . .
else if(condition_n) {
    statement_n;
}
else {
    statement-n;
}

Practical LearningPractical Learning: Introducing if...else if Conditions

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click ASP.NET Application (.NET Framework) and change the project Name to CompoundInterest2
  3. Click OK
  4. In the New ASP.NET Application menu, make sure Empty is selected and click OK
  5. In the Solution Explorer, right-click CompoundInterest2 -> Add -> New Folder
  6. Type Content and press Enter
  7. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  8. Type Site and press Enter
  9. Change the code as follows:
    table            { width:       100%   }
    .ctrl-formatting { width:       80px;  }
    .boldness        { font-weight: bold;  }
    .alignment       { text-align:  center }
    .left-col {
        width: 120px;
        font-weight: bold }
    .contents {
        width:  550px;
        margin: auto; }
  10. In the Solution Explorer, right-click CompoundInterest2 -> Add -> Add ASP.NET Folder -> App_Code
  11. In the Solution Explorer, right-click App_Code -> Add -> New Item...
  12. In the left frame of the Add New Item dialog box, expand Web and click Razor
  13. In the middle list, click Helper (Razor v3)
  14. Replace the name with CompoundEvaluations
  15. Click Add
  16. Create a helper as follows:
    @helper Calculate(double principal, double iRate, string strFrequency, double periods) {
        double frequency = 0.00;
        string strFutureValue = "0.00";
        string strInterestEarned = "0.00";
    
        if (strFrequency == "Daily")
        {
            frequency = 365.00;
        }
        else if (strFrequency == "Weekly")
        {
            frequency = 52.00;
        }
        else if (strFrequency == "Monthly")
        {
            frequency = 12.00;
        }
        else if (strFrequency == "Quaterly")
        {
            frequency = 4.00;
        }
        else if (strFrequency == "Semiannually")
        {
            frequency = 2.00;
        }
        else if (strFrequency == "Annually")
        {
            frequency = 1.00;
        }
    
        double futureValue = principal * Math.Pow((1.00 + (iRate / frequency)), frequency * periods);
        double interestEarned = futureValue - principal;
    
        strInterestEarned = interestEarned.ToString("F");
        strFutureValue = futureValue.ToString("F");
    
        <form name="frmResults" method="post">
            <table>
                <tr>
                    <td style="width: 120px">Interest Earned:</td>
                    <td><input type="text" name="txtInterestEarned" style="width: 100px" value="@strInterestEarned" /></td>
                    <td>Future Value:</td>
                    <td><input type="text" name="txtFutureValue" class="ctrl-formatting" value="@strFutureValue" /></td>
                </tr>
            </table>
        </form>
    }
  17. In the Solution Explorer, click CompoundInterest2 to select it
  18. On the main menu, click Project -> Add New Item...
  19. In the left list, expand Web and click Razor
  20. In the middle list, click Web Page (Razor v3)
  21. Change the name to Index
  22. Click Add
  23. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Compound Interest</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
        @{
            double rate = 0;
            double periods = 0;
            double principal = 0.00;
            string strFrequency = "";
            double interestRate = 0.00;
    
            if (IsPost)
            {
                principal = Convert.ToDouble(Request["txtPrincipal"]);
                interestRate = Convert.ToDouble(Request["txtInterestRate"]);
                periods = Convert.ToDouble(Request["txtPeriods"]);
    
                rate = interestRate / 100.00;
                strFrequency = Request["rdoCompoundFrequency"];
            }
        }
    
        <div class="contents">
            <h2 class="alignment">Compound Interest</h2>
    
            <form name="frmCompoundInterest" method="post">
                <table>
                    <tr>
                        <td class="left-col">Principal:</td>
                        <td><input type="text" name="txtPrincipal" class="ctrl-formatting" value="@principal" /></td>
                        <td rowspan="3" class="boldness">
                            Compound Frequency
                            <table>
                                <tr>
                                    <td>Daily</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="Daily" /></td>
                                    <td style="width: 30px">&nbsp;</td>
                                    <td>Quaterly</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="Quaterly" /></td>
                                </tr>
                                <tr>
                                    <td>Weekly</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="Weekly" /></td>
                                    <td>&nbsp;</td>
                                    <td>Semiannually</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="Semiannually" /></td>
                                </tr>
                                <tr>
                                    <td>Monthly</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="Monthly" /></td>
                                    <td>&nbsp;</td>
                                    <td>Annually</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="Annually" /></td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr>
                        <td class="boldness">Interest Rate:</td>
                        <td><input type="text" name="txtInterestRate" class="ctrl-formatting" value="@interestRate" /> %</td>
                    </tr>
                    <tr>
                        <td class="boldness">Periods:</td>
                        <td><input type="text" name="txtPeriods" class="ctrl-formatting" value="@periods" /> Years</td>
                    </tr>
                </table>
    
                <p class="alignment"><input type="submit" name="btnCalculate" style="width: 400px" value="Calculate" /></p>
            </form>
    
            @CompoundEvaluations.Calculate(@principal, @rate, @strFrequency, @periods)
        </div>
    </body>
    </html>
  24. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Finding Out Whether a Value is Greater Than Another Value

  25. In the Principal text box, type a number such as 3450
  26. In the Interest Rate text box, type a number such as 12.50

  27. In the Periods text box, type a natural number such as 4
  28. In the Compound Frequency group box, click one of the radio buttons such as Monthly:

    Finding Out Whether a Value is Greater Than Another Value

  29. Click the Calculate button:

    Finding Out Whether a Value is Greater Than Another Value

  30. Close the browser and return to your programming environment

Options on Conditional Statements

Going To a Statement

In the flow of your code, you can jump from one statement or line to another. To make this possible, the C# language forvides an operator named goto. Before using it, first create or insert a name on a particular section of code or in a method. The name, also called a label, is made of one word and it can be anything. That name is followed by a colon ":". Here is an example:

@{ 
    
proposition:
    
}

In the same way, you can create as many labels as you want. The name of each label must be unique among the other labels in the same section of code (in the same scope). Here are examples:

@{ 
    
proposition:

something:

TimeToLeave:
    
}

After creating the label(s), you can create a condition so that, when that condition is true, code execution would jump to a designated label. To do this, in the body of the condition, type goto followed by the label. Here are examples:

@{ 
    int nbr = 248;
    double result = 0;

    if( nbr < 200)
    {
        goto proposition;
    }
    else
    {
        goto something;
    }

proposition:
    result = 245.55;

something:
    result = 105.75;
}

Negating a Statement

As you should be aware by now, Boolean algebra stands by two values, True and False, that are opposite each other. If you have a Boolean value or expression, to let you validate its opposite, the C-based languages provide the ! operator that is used to get the logical reverse of a Boolean value or of a Boolean expression. The formula to use it is:

!expression

To use this operator, type ! followed by a logical expression. The expression can be a simple Boolean value. To make the code easier to read, it is a good idea to put the negative expression in parentheses. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    public void Create()
    {
        bool employeeIsFullTime = true;

       string opposite = (!employeeIsFullTime).ToString();
    }
}

In this case, the ! (Not) operator is used to change the logical value of the variable. When a Boolean variable has been "notted", its logical value has changed. If the logical value was true, it would be changed to false and vice versa. Therefore, you can inverse the logical value of a Boolean variable by "notting" or not "notting" it.

Conditional Returns of Methods

When performing its assignment, a method can encounter different situations, a method can return only one value but you can make it produce a result that depends on some condition.

Practical LearningPractical Learning: Conditionally Returning a Value

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click ASP.NET Web Application (.NET Framework) and set the project Name to DepartmentStore07
  3. Click OK
  4. In the New ASP.NET Web Application dialog box, click Empty and click OK
  5. In the Solution Explorer, right-click DepartmentStore07 -> Add ASP.NET Folder -> App_Code
  6. In the Solution Explorer, right-click App_Code -> Add -> Class..
  7. Change the name to StoreItem
  8. Press Enter
  9. Change the code as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace DepartmentStore07.App_Code
    {
        public class StoreItem
        {
            public int ItemNumber { get; set; }
            public string ItemName { get; set; }
            public string Size { get; set; }
            public decimal UnitPrice { get; set; }
    
            public decimal GetDiscountRate(int days)
            {
                decimal discountRate = 0.00M;
    
                if (days > 70)
                    discountRate = 70;
                else if (days > 50)
                    discountRate = 50;
                else if (days > 30)
                    discountRate = 35;
                else if (days > 15)
                    discountRate = 15;
    
                return discountRate;
            }
    
            public decimal GetDiscountAmount(decimal rate)
            {
                decimal discountAmount = 0.00M;
    
                if (rate == 0.00M)
                    discountAmount = 0.00M;
                else
                    discountAmount = UnitPrice * rate / 100.00M;
    
                return discountAmount;
            }
        }
    }
  10. In the Solution Explorer, right-click DepartmentStore07 -> Add -> New Folder
  11. Type Content and press Enter
  12. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  13. Type Site and press Enter
  14. Change the code as follows:
    body {
    }
    
    .ctrl-format { width:      80px   }
    .centr-align { text-align: center }
    .col-caption { width:      125px  }
    .col-second  { width:      110px  }
    .col-third   { width:      100px  }
    .whole
    {
        margin: auto;
        width: 460px; }
  15. In the Solution Explorer, right-click DepartmentStore07 -> Add -> New Item...
  16. In the left list, expand Web and click Razor
  17. In the middle list, click Web Page (Razor v3)
  18. Set the name as Index
  19. Press Enter
  20. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Department Store - Inventory Creation</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    @{
        int daysInStore = 0;
        string strMarkedPrice = "0.00";
        string strDiscountRate = "0.00";
        string strDiscountedAmount = "0.00";
        DepartmentStore07.App_Code.StoreItem si = new DepartmentStore07.App_Code.StoreItem();
    
        if (IsPost)
        {
            si = new DepartmentStore07.App_Code.StoreItem();
            si.ItemNumber = Request["txtItemNumber"].AsInt();
            si.ItemName = Request["txtItemName"];
            si.UnitPrice = Request["txtUnitPrice"].AsDecimal();
            daysInStore = Request["txtDaysInStore"].AsInt();
    
            decimal discountRate = si.GetDiscountRate(daysInStore);
            decimal discountedAmount = si.GetDiscountAmount(discountRate);
            decimal markedPrice = si.UnitPrice - discountedAmount;
    
            strDiscountRate = discountRate.ToString("F");
            strDiscountedAmount = discountedAmount.ToString("F");
            strMarkedPrice = markedPrice.ToString("F");
        }
    }
    <div class="whole">
        <h2 class="centr-align">Department Store</h2>
        <h3 class="centr-align">Inventory Creation</h3>
    
        <form name="frmEvaluation" method="post">
            <table style="width: 100%">
                <tr>
                    <td class="col-caption">Item #:</td>
                    <td><input type="text" name="txtItemNumber" class="ctrl-format" value="@si.ItemNumber" /></td>
                </tr>
            </table>
            <table style="width: 460px">
                <tr>
                    <td class="col-caption">Item Name:</td>
                    <td><input type="text" name="txtItemName" style="width: 300px" value="@si.ItemName" /></td>
                </tr>
            </table>
            <table style="width: 460px">
                <tr>
                    <td class="col-caption">Unit Price:</td>
                    <td class="col-second"><input type="text" name="txtUnitPrice" class="ctrl-format" value="@si.UnitPrice" /></td>
                    <td class="col-third">Days in Store:</td>
                    <td><input type="text" name="txtDaysInStore" class="ctrl-format" value="@daysInStore" /></td>
                </tr>
            </table>
    
            <table style="width: 460px">
                <tr>
                    <td class="col-caption">&nbsp;</td>
                    <td style="text-align: left"><input type="submit" name="btnEvaluate" style="width: 310px" value="Evaluate Sale Record" /></td>
                </tr>
            </table>
    
            <table style="width: 460px">
                <tr>
                    <td class="col-caption">Item #:</td>
                    <td class="col-second"><input type="text" name="txtRecordItemNumber" class="ctrl-format" value="@si.ItemNumber" /></td>
                    <td class="col-third">Discount Rate:</td>
                    <td><input type="text" name="txtDiscountRate" class="ctrl-format" value="@strDiscountRate" /></td>
                </tr>
            </table>
            <table style="width: 460px">
                <tr>
                    <td class="col-caption">Item Name:</td>
                    <td><input type="text" name="txtRecordItemName" style="width: 300px" value="@si.ItemName" /></td>
                </tr>
            </table>
            <table style="width: 460px">
                <tr>
                    <td class="col-caption">Discount Amount:</td>
                    <td class="col-second"><input type="text" name="txtDiscountAmount" class="ctrl-format" value="@strDiscountedAmount" /></td>
                    <td class="col-third">Marked Price:</td>
                    <td><input type="text" name="txtMarkedPrice" class="ctrl-format" value="@strMarkedPrice" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  21. To execute the project, press Ctrl + F5:

    Conditionally Returning a Value

  22. In the text boxes above the Evaluate button, enter some values as follows:
    Item #:        258408
    Item Name:     Pinstripe Pencil Skirt
    Unit Price:    94.95
    Days in Store: 36

    Conditionally Returning a Value

  23. Click the Evaluate Sale Record button:

    Conditionally Returning a Value

  24. Close the form and return to your programming environment
  25. In our examples, we first declared a variable that was going to hold the value to return. This is not always necessary. If you already have the value or the expression to return, you can precede it with the return keyword. You can repeat this for each section where the value or expression can/must be returned.
    For examples, access the StoreItem.cs file and change the code in the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace DepartmentStore07
    {
        public class StoreItem
        {
            public int ItemNumber { get; set; }
            public string ItemName { get; set; }
            public string Size { get; set; }
            public decimal UnitPrice { get; set; }
    
            public decimal GetDiscountRate(int days)
            {
                if (days > 70)
                    return 70;
                else if (days > 50)
                    return 50;
                else if (days > 30)
                    return 35;
                else if (days > 15)
                    return 15;
                else
                    return 0;
            }
    
            public decimal GetDiscountAmount(decimal rate)
            {
                if (rate == 0)
                    return 0;
                else
                    return UnitPrice * rate / 100;
            }
        }
    }
  26. To execute the application, press Ctrl + F5
  27. Close the browser and return to your programming environment

Returning From a Method

Normally, when defining a void method, it doesn't return a value. Here is an example:

public class Exercise
{
    private void Show()
    {
    }
}

In reality, a void method can perform a return, as long as it does not return a true value. This is used to signal to the compiler that it is time to get out of the method. To add such as flag, in the appropriate section of the void method, simply type return;. Here is an example:

public class Exercise
{
    private void Show()
    {
        Blah Blah Blah
        
        return;
    }
}

In this case, the return; statement doesn't serve any true purpose. It can be made useful when associated with a conditional statement.

Introduction to Recursion

Recursion if the ability for a method (or functtion) to call itself. A possible problem is that the method could keep calling itself and never stops. Therefore, the method must define how it would stop calling itself and get out of the body of the method.

A type of formula to create a recursive method is:

return-value method-name(parameter(s), if any)
{
    Optional Action . . .
    method-name();
    Optionan Action . . .
}

A recursive method starts with a return value. If it would not return a value, you can define it with void. After its name, the method can use 0, one, or more parameters. Most of the time, a recursive method uses at least one parameter that it would modify. In the body of the method, you can take the necessary actions. There are no particular steps to follow when implementing a recursive method but there are two main rules to observe:

For an example of counting decrementing odd numbers, you could start by creating a method that uses a parameter of type integer. To exercise some control on the lowest possible values, we will consider only positive numbers. In the body of the method, we will display the current value of the argument, subtract 2, and recall the method itself. Here is our method:

public void OddNumbers(int a)
{
    if (a >= 1)
    {
        Number += a;

        a -= 2;
        OddNumbers(a);
    }
}
-------------------------------------------
@{ 
    Exercise.Controllers.HomeController hc = new Exercise.Controllers.HomeController();

    const int number = 9;
    hc.OddNumbers(number);
}

<p>Number: @hc.Number</p>

Notice that the method calls itself in its body.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next