ms_learn_csharp/013_eval_boolean_expressions/013_csharp.md

613 lines
20 KiB
Markdown
Raw Permalink Normal View History

2024-07-19 20:30:50 -04:00
# Introduction
Decision logic is based on expressions, known as Boolean expressions that
evaluates to "true" or "false". Developers use various types of operators to
create Boolean expressions that meet their coding requirements. When the
expressions are evaluated, the code execution branches based on the result.
The C# language supports a wide range of operators (such as equality,
comparison, and Boolean operators), each of which serves a specific purpose
when implementing decision logic.
Suppose you've been selected to work on a series of C# console applications
that are used to process customer data and user supplied inputs. Each
application requires you to implement decision logic that achieves data
processing requirements and associated business rules. The data processing
requirements and business rules vary for each application. For example,
applications that process customer orders might need to evaluate the status of
the customer before taking any action. To prepare for this upcoming assignment,
you'll complete some practice activities that implement Boolean expressions
and C# operators.
In this module, you learn about Boolean expressions, and you use different
types of operators to evaluate expressions for equality, inequality, and
comparison. You also learn to use a special inline version of an if statement
(a conditional operator) that produces an "either / or" result.
By the end of this module, you are able to write code using any combination of
C# operators to implement decision logic in your applications.
### Learning objectives
In this module, you will:
- Use operators to create Boolean expressions that test for comparison and equality.
- Use built-in methods of the string class to perform better evaluations on strings.
- Use the negation operator to test for the opposite of a given condition.
- Use the conditional operator to perform an inline evaluation.
#### Prerequisites:
- Experience with basic coding tasks such as instantiating variables, using
various data types, and sending output to a console window.
- Experience using the `if-elseif-else` construct.
- Experience using the `Random` class to generate a random number.
- Experience using `dotnet` to create and run simple console applications.
---
## Exercise
### Evaluate an expression
Decision logic is used to establish alternative pathways through your code,
where the decision about which path to follow is based on the evaluation of an
expression. For example, you might write some code that executes one of two
paths based on a user's input. If the user enters the letter "a", your code
will execute one code block. If they enter the letter "b", your code will
execute a different code block. In this example, you're controlling the
execution path based on the value assigned to a string. Your code selects an
execution path based on an expression, how that expression is evaluated, and
the underlying logic used to define the paths.
Examining how to construct and evaluate an expression is a good place to
start.
### What is an expression?
An expression is any combination of values (literal or variable), operators,
and methods that return a single value. A statement is a complete instruction
in C#, and statements are comprised of one or more expressions. For example,
the following `if` statement contains a single expression that returns a
single value:
```cs
if (myName == "Luiz")
```
You might have been thinking that the value returned by an expression would be
a number or maybe a string. It's true that application developers use
different types of expressions for different purposes. In this case, when you
're developing an if selection statement, you'll be using an expression that
returns either true or false. Developers refer to this type of expression as a
Boolean expression. When your code includes a Boolean expression, return value
is always a single `true` or `false` value.
Boolean expressions are important because your code can use these expressions
to decide which block of code to execute.
There are many different types of operators that you can use within a Boolean
expression. For example, the `if` statement above uses the equality operator
`==` to check whether a string variable is assigned a particular value. The
operator that you choose will depend on the available code paths, the
conditions associated with the paths, and the underlying application logic.
### Evaluating equality and inequality
One of the most common code evaluations is a check to see whether two values
are equal. When checking for equality, you'll locate the equality operator `==`
between the two values being checked. If the values on either side of the
equality operator are equivalent, then the expression will return `true`.
Otherwise, it will return `false`.
Conversely, you might also need to check whether two values aren't equal. To
check for inequality, you'll use the inequality operator `!=` between the two
values.
You might wonder why you need both equality and inequality operators. The
reason will become clearer as you learn how to create branching statements and
begin to write real world code. Two operators that perform opposite tasks
allow you to be more expressive and compact.
Now it's time to prepare your coding environment and begin writing code that
evaluates Boolean expressions.
#### Prepare your coding environment
At the Terminal command prompt, to create a new console application in a
specified folder, type dotnet new console -o ./path_to_projects/TestProject
and then press Enter.
### Use the equality operator
Ensure that you IDE open and Program.cs displayed in the Editor.
Type the following code into the Visual Studio Code Editor.
```cs
Console.WriteLine("a" == "a");
Console.WriteLine("a" == "A");
Console.WriteLine(1 == 2);
string myValue = "a";
Console.WriteLine(myValue == "a");
```
The Program.cs file must be saved before building or running the code.
At the Terminal command prompt, to run your code, type `dotnet run` and then
press Enter.
You should see the following output.
```txt
True
False
False
True
```
### Improve the check for string equality using the string's built-in helper methods
You might be surprised that the line `Console.WriteLine("a" == "A");` outputs
`false`. When comparing strings, case matters.
Also, consider this line of code:
```cs
Console.WriteLine("a" == "a ");
```
Here you've added a space character at the end of the string. This expression
will also output false.
In some cases, having a space character before or after the text might be
perfectly acceptable. However, if you need to accept a match that isn't exact,
you can "massage" the data first. "Massaging" the data means that you perform
some cleanup before you perform a comparison for equality.
For example, consider the case when you're collecting user input inside a loop.
After each value is entered, you could provide the user with a prompt to
determine if they want to continue, such as `Do you want to continue (Y/N)?`.
If the user wants to continue, they will probably enter either `y` or `Y`. You
'll want your code to interpret both values equally, even though `y` isn't
equivalent to `Y`.
Before you check two string values for equality, especially when one or both
values were entered by a user, you should:
- Make sure both strings are all upper-case or all lower-case using the
`ToUpper()` or `ToLower()` helper method on any string value.
- Remove any leading or trailing blank spaces using the `Trim()` helper method
on any string value.
You can improve the previous equality check by chaining these two helper
methods on both values, as shown in the following code listing:
Replace the code in the Visual Studio Code Editor with the following code:
```cs
string value1 = " a";
string value2 = "A ";
Console.WriteLine(value1.Trim().ToLower() == value2.Trim().ToLower());
```
Notice that when you run the code this time, it outputs **True**.
### Use the inequality operator
Use the line comment operator `//` to comment out all of the code from the
previous step.
Type the following code into the Visual Studio Code Editor.
```cs
Console.WriteLine("a" != "a");
Console.WriteLine("a" != "A");
Console.WriteLine(1 != 2);
string myValue = "a";
Console.WriteLine(myValue != "a");
```
Save your code file, and then run your code.
You should see the following output.
```txt
False
True
True
False
False
```
As you would expect, the result when using the inequality operator is the
opposite of what you saw when using the equality operator. That means that
your code will branch in the opposite manner as well, which can be exactly
what you want.
### Evaluating comparisons
When working with numeric data types, you might want to determine if a value is larger or smaller than another value. Use the following operators to perform these types of comparisons:
- Greater than `>`
- Less than `<`
- Greater than or equal to `>=`
- Less than or equal to `<=`
Naturally, the `==` and `!=` operators that you used to compare string values
above will also work when comparing numeric data types.
#### Use the Comparison operators
Use the line comment operator `//` to comment out all of the code from the
previous task.
Type the following code into the Visual Studio Code Editor.
```cs
Console.WriteLine(1 > 2);
Console.WriteLine(1 < 2);
Console.WriteLine(1 >= 1);
Console.WriteLine(1 <= 1);
```
Save your code file, and then build and run your code.
You should see the following output:
```txt
False
True
True
True
```
### Methods that return a Boolean value
Some methods return a Boolean value (`true` or `false`). In the following
exercise, you'll use a built-in method of the String class to determine
whether or not a larger string contains a specific word or phrase that's
significant to your application.
> Note
> Some data types have methods that perform helpful utility tasks. The String
data type has many of these. Several return a Boolean value including
`Contains()`, StartsWith(), and EndsWith(). You can learn more about them in
the Microsoft Learn module "Manipulate alphanumeric data using String class
methods in C#".
#### Use a method that returns a Boolean
Use the line comment operator `//` to comment out all of the code from the
previous step.
Type the following code into the editor.
```cs
string pangram = "The quick brown fox jumps over the lazy dog.";
Console.WriteLine(pangram.Contains("fox"));
Console.WriteLine(pangram.Contains("cow"));
```
Save your code file, and then build and run your code.
You should see the following output.
```txt
True
False
```
### What is logical negation?
The term "Logical Negation" refers to the unary negation operator `!.` Some
people call this operator the "not operator". When you place the `!` operator
before a conditional expression (or any code that's evaluated to either `true`
or `false`), it forces your code to reverse its evaluation of the operand.
When logical negation is applied, the evaluation produces `true` , if the
operand evaluates to `false` , and `false` , if the operand evaluates to `true`.
Here is an example that might help you to see the connection between these
ideas. The following two lines of code produce the same result. The second
line is more compact.
```cs
// These two lines of code will create the same output
Console.WriteLine(pangram.Contains("fox") == false);
Console.WriteLine(!pangram.Contains("fox"));
```
#### Use the Logical Negation operator
Use the line comment operator `//` to comment out all of the code from the
previous step.
Type the following.
```cs
string pangram = "The quick brown fox jumps over the lazy dog.";
Console.WriteLine(!pangram.Contains("fox"));
Console.WriteLine(!pangram.Contains("cow"));
```
Save your code file, and then build and run your code.
You should see the following output.
```txt
False
True
```
#### Inequality operator versus logical negation
The inequality operator `!=` includes a `!` character, but should not be
confused with logical negation. The inequality operator returns `true` if its
operands aren't equal, and returns false if the operands are equal. For the
operands of the built-in types, the expression `x != y` produces the same
result as the expression `!(x == y)` (an example of logical negation).
The following code sample demonstrates the use of the `!=` operator:
```cs
int a = 7;
int b = 6;
Console.WriteLine(a != b); // output: True
string s1 = "Hello";
string s2 = "Hello";
Console.WriteLine(s1 != s2); // output: False
```
### Recap
Here's the main takeaways you learned about evaluating Boolean expressions so
far:
- There are many different kinds of expressions that evaluate to either `true`
or `false`.
- Evaluate equality using the `==` operator.
- Evaluating equality of strings requires you to consider the possibility that
the strings have different case and leading or trailing spaces. Depending on
your situation, use the `ToLower()` or `ToUpper()` helper methods, and the
`Trim()` helper method to improve the likelihood that two strings are equal.
- Evaluate inequality using the `!=` operator.
- Evaluate greater than, less than and similar operations using comparison
operators like `>`, `<`, `>=`, and `<=`.
- If a method returns a bool, it can be used as a Boolean expression.
- Use the logical negation operator `!` to evaluate the opposite of a given
expression.
---
## 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, the purchase is eligible for
a $100 discount. If the purchase amount is $1000 or less, the purchase is
eligible for a $50 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:
```cs
<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 on their purchase.
#### Add code that uses a conditional operator
Type the following code into the editor.
```cs
int saleAmount = 1001;
int discount = saleAmount > 1000 ? 100 : 50;
Console.WriteLine($"Discount: {discount}");
```
The Program.cs file must be saved before building or running the code.
When you run the code, you should see the following output:
```txt
Discount: 100
```
#### Use the conditional operator inline
You can compact this code even more by eliminating the temporary variable
discount.
Update your code in the editor as follows:
```txt
int saleAmount = 1001;
// int discount = saleAmount > 1000 ? 100 : 50;
Console.WriteLine($"Discount: {(saleAmount > 1000 ? 100 : 50)}");
```
At the Terminal command prompt, to run your code, type `dotnet run` and then
press Enter.
Notice that the output is the same.
Take a minute to examine the updated `Console.WriteLine()` statement.
Notice that it's necessary to wrap the entire conditional operator statement
in parentheses. The parentheses ensure that the runtime understands your intent,
which is to display the conditional result rather than the result of
evaluating the condition (saleAmount > 1000).
> Note
> While this particular example is compact and shows what is possible, it is a
bit more difficult to read. It's not always a good idea to combine lines of
code, especially when it adversely affects the overall readability of your code.
This is often a subjective judgment call.
### Recap
You should remember the following facts about the conditional operator:
- You can use the conditional operator to reduce the size of your code, but
you should ensure that the resulting code is easily readable.
- You can use the conditional operator when you need to return a value that's
based on a binary condition. Your code will return the first option when the
condition evaluates to true, and it will return the second option when the
condition evaluates to false.
---
## Exercise
### Complete a challenge activity using conditional operators
Code challenges will reinforce what you've learned and help you gain some
confidence before continuing on.
### Conditional operator challenge
In this challenge, you'll implement a conditional operator to simulate a "coin
flip". The resulting decision logic will display either `heads` or `tails`.
### Code challenge: write code to display the result of a coin flip
Here are your challenge requirements:
- Use the Random class to generate a value.
- Consider the range of numbers that is required.
- Based on the value generated, use the conditional operator to display either
`heads` or `tails`.
- There should be a 50% chance that the result is either heads or tails.
Your code should be easy to read, but with as few lines as possible.
You should be able to accomplish the desired result in three lines of code.
---
## Exercise
### Complete a challenge activity using Boolean expressions
Code challenges will reinforce what you've learned and help you gain some
confidence before continuing on.
### Decision logic challenge
In this challenge, you'll implement decision logic based on a series of
business rules. The business rules specify the access that will be granted to
users based on their role-based permissions and their career level. Code
branches will display a different message to the user depending on their
permissions and level.
#### Initialize permission and level values
Ensure that you have an empty Program.cs file open.
Type the following code into the editor:
```cs
string permission = "Admin|Manager";
int level = 55;
```
Review the initial code lines.
Your application will be using a combination of `permission` and `level` to
apply/evaluate the business rules in this challenge scenario. The full list of
conditions for business rules is specified in the next step. Your completed
solution must use `permission` and `level`.
> Tip
> To sufficiently test all of the combinations for permission and level that
are described in the business rules below, you will need to assign additional
values to these variables and run the application multiple times.
#### Implement business rules
> Important
> You will need to use the `Contains()` helper method to determine whether the
value assigned to the `permission` string contains one of the permission
values specified by the "business rules". For example, the expression
`permission.Contains("Admin")` will return `true` when using the initial data
values specified in the code above.
Here are the **Business Rules** that your solution must satisfy:
- If the user is an Admin with a level greater than 55, output the message:
```txt
Welcome, Super Admin user.
```
- If the user is an Admin with a level less than or equal to 55, output the
message:
```txt
Welcome, Admin user.
```
- If the user is a Manager with a level 20 or greater, output the message:
```txt
Contact an Admin for access.
```
- If the user is a Manager with a level less than 20, output the message:
```txt
You do not have sufficient privileges.
```
- If the user is not an Admin or a Manager, output the message:
```txt
You do not have sufficient privileges.
```
Update your Program.cs code to accommodate each of the business rules.
Save your code.
#### Test your solution using the initial data values suggested
1. Build and run your code.
2. Evaluate the output.
When you run your code, including the initial configuration data, you should
see the following output:
```txt
Welcome, Admin user.
```
#### Test for the other business rules
1. Update the values assigned to permission and level.
2. Save and run your code.
3. Evaluate the output to verify that the other business rules are satisfied.
---