Using Boolean expressions logic and Conditobal operator
Conditional operator

Using Boolean expressions logic and Conditobal operator


Introduction

When adding decision logic to your application, you’ll need to evaluate many different kinds of conditions. To express those conditions adequately, you’ll need to have a full complement of operators.

Suppose you need to determine whether one value is greater, equal to, or less than another value. Or, what if you need to ensure a user’s input matches a specific value. Or, what if you need to make sure the value returned from a method does not indicate failure.

In these cases, you use many different kinds of Boolean expressions that use a wide array of operators.


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 programming, and statements are comprised of one or more expressions.

There are many different categories of expressions, but when working with decision statements, we’re interested in Boolean expressions. In a Boolean expression, the runtime evaluates the values, operators, and methods to return a single true or false value.

Boolean Expressions

Decision logic” and “branching logic” are terms programmers use to describe the change in execution path based on the evaluation of some expression. For example, we may write code that evaluates user input. If the value the user inputs is equal to the string value “a”, execute one code block. If the value the user inputs is equal to the string value “b”, execute a different code block. Here, we’re changing the execution path of our application based on user input. This is what is meant by the terms “branching” and “decision”.

Evaluating equality and inequality

Use the equality operator

Console.WriteLine("a" == "a");
Console.WriteLine("a" == "a "); // A blank space was added at the end of the string.
Console.WriteLine("a" == "A");
Console.WriteLine(1 == 2);
string myValue = "a";
Console.WriteLine(myValue == "a");        

You should see the following output when you run the code.

True False False False True

Improve the check for string equality using the string’s built-in helper methods in C#

Let’s improve the previous check for equality by chaining these two methods on both values in the following code listing:

string value1 = " a";
string value2 = "A ";
Console.WriteLine(value1.Trim().ToLower() == value2.Trim().ToLower());        

When you run the code this time, the output will be true.

Trim()?—?removes the space around the string

ToLower()?—?forces all the letters to lowercase

Use the inequality operator

Console.WriteLine("a" != "a");
Console.WriteLine("a" != "A");
Console.WriteLine(1 != 2);
string myValue = "a";
Console.WriteLine(myValue != "a");        

Now run the code. You should see the following output.

False True True False

Evaluating comparisons

When working with numeric data types, you’ll want to determine if one value is larger, smaller, or equal to 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 <=

Use the Comparison operators

Console.WriteLine(1 > 2);
Console.WriteLine(1 < 2);
Console.WriteLine(1 >= 1);
Console.WriteLine(1 <= 1);        

You should see the following output when you the code

False True True True

Methods that return a Boolean value

Some methods return a Boolean value. You can think of these types of methods as queries. Such as Contains(), StartsWith(), and EndsWith().

Use a method invocation expression

string pangram = "The quick brown fox jumps over the lazy dog.";
Console.WriteLine(pangram.Contains("fox"));
Console.WriteLine(pangram.Contains("cow"));        

You should see the following output when you the code.

True False

What is logical negation?

The term “Logical Negation” refers to the?! operator. Some people simply call this the “not operator”. Adding the?! operator before a conditional expression like a method call checks to ensure the expression is false.

And just to hopefully help you see the connections between these ideas, the following two lines of code do the same thing. The second line is more compact.

string pangram = "The quick brown fox jumps over the lazy dog.";
Console.WriteLine(! pangram.Contains("fox"));
Console.WriteLine(!pangram.Contains("cow"));        

You should see the following output when the output.

False True

conditional operator

What is the conditional operator?

The conditional operator??:, commonly known as the ternary conditional operator, evaluates a Boolean expression, and returns the result of evaluating one of two expressions, depending on whether the Boolean expression evaluates to true or false.

Here’s the basic form:

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

Let’s use the conditional operator to display a message to the customer with their promotional discount based on whether they’ve spent more than $1000 on their purchase.

int saleAmount = 1001;
int discount = saleAmount > 1000 ? 100 : 50;
Console.WriteLine($"Discount: {discount}");        

When you run the code, you should see the following output.

OutputCopy Discount: 100

Use the conditional operator inline

We can compact this code even more by eliminating the temporary variable discount.

int saleAmount = 1001;
Console.WriteLine($"Discount: {(saleAmount > 1000 ? 100 : 50)}");        

If you run the code, the output is the same.

It’s necessary to wrap the entire conditional operator statement in parentheses so that the runtime doesn’t mistake your intent (before evaluating the condition).



要查看或添加评论,请登录

Ferdinand Charles的更多文章

社区洞察

其他会员也浏览了