Exercise – Implement the conditional operator

Suppose you need to quickly determine whether a customer’s purchase is eligible for a promotional discount. The details for the promotion indicate that when a purchase value is greater than 1000 euros, the purchase is eligible for a 100 euro discount. If the purchase amount is 1000 euros or less, the purchase is eligible for a 50 euro discount.

While you could certainly use the if ... elseif ... else branching construct to express this business rule, using the conditional operator to evaluate eligibility for the promotional discount might be a better choice. The conditional operator uses a compact format that saves a few lines of code and possibly makes the intent of the code clearer.

What is the conditional operator?

The conditional operator ?: evaluates a Boolean expression and returns one of two results depending on whether the Boolean expression evaluates to true or false. The conditional operator is commonly referred to as the ternary conditional operator.

Here’s the basic form:

c#Copy

<evaluate this condition> ? <if condition is true, return this value> : <if condition is false, return this value>

Take a minute to consider how you’d apply the conditional operator to the promotional discount scenario. Your goal is to display a message to the customer that shows their discount percentage. The amount of their discount will be based on whether they’ve spent more than 1000 euros on their purchase.

Add code that uses a conditional operator

  1. Ensure that you have an empty Program.cs file open in Visual Studio Code. If necessary, open Visual Studio Code, and then complete the following steps to prepare a Program.cs file in the Editor:
    1. On the File menu, select Open Folder.
    2. Use the Open Folder dialog to navigate to, and then open, the CsharpProjects folder.
    3. In the Visual Studio Code EXPLORER panel, select Program.cs.
    4. On the Visual Studio Code Selection menu, select Select All, and then press the Delete key.
  2. Type the following code into the Visual Studio Code Editor.c#Copyint saleAmount = 1001; int discount = saleAmount > 1000 ? 100 : 50; Console.WriteLine($"Discount: {discount}");
  3. On the Visual Studio Code File menu, select Save.The Program.cs file must be saved before building or running the code.
  4. In the EXPLORER panel, to open a Terminal at your TestProject folder location, right-click TestProject, and then select Open in Integrated Terminal.A Terminal panel that displays a command prompt should now be open. The command prompt should display the folder path for your TestProject folder location.
  5. At the Terminal command prompt, to run your code, type dotnet run and then press Enter.When you run the code, you should see the following output:dosCopyDiscount: 100

ccie certification training courses malaysia

Leave a Reply

Your email address will not be published. Required fields are marked *