And
|| Or
! Not

For example, consider the following code example:

if (age < 12 || height > 120) {

Console.WriteLine('Student price applies');

}

In this case, student price applies if either the age is less than 12, or the height is less than 120cm. As long as at least one of the conditions evaluates to true, the statement is true. Following is the truth table for the Or (||) operator.

Operand A Operand B Result
false false false
false true true
true false true
true true true

However, if the condition is changed such that student price applies only if a person is less than 12 years old and with height less than 120cm, the statement would be rewritten as:

if (age < 12 && height > 120) {

 Console.WriteLine('Student price applies');

}

The truth table for the And (&&) operator follows.

Operand A Operand B Result
false false false
false true false
true false false
true true true

The Not operator (!) negates the result of an expression. For example, if student price does not apply to those more than 12 years old, you could write the expression like this:

if (!(age >= 12))

 Console.WriteLine('Student price does not apply');

Following is the truth table for the Not operator.

Operand A Result
false true
true false
Short-Circuit Evaluation

C# uses short-circuiting when evaluating logical operators. In short-circuiting, the second argument in a

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату