DEV Community

Cover image for Conditional expressions C#
Zafar Urakov
Zafar Urakov

Posted on • Edited on

Conditional expressions C#

A separate set of operations represents conditional expressions. Such operations return a boolean value, that is, a value of type bool: true if the expression is true, and false if the expression is false. These operations include comparison operations and logical operations.

Comparison operations

Comparison operators compare two operands and return a bool - true if the expression is true and false if the expression is false.

  • ==

Compares two operands for equality. If they are equal, then the operation returns true, if not equal, then false is returned:

int firstNumber = 10;
int secondNumber = 4;
bool thirdNumber = firstNumber == secondNumber; // false
Enter fullscreen mode Exit fullscreen mode
  • !=

Compares two operands and returns true if the operands are not equal and false if they are equal.

int firstNumber  = 10;
int secondNumber = 4;
bool thirdNumber = firstNumber != secondNumber; // true
bool fourthNumber = firstNumber != 10; // false
Enter fullscreen mode Exit fullscreen mode
  • <

Operation "less than". Return true the first operand is less than second, and false if the first operand is greater than the second:

int firstNumber  = 10;
int SecondNumber = 4;
bool thirdNumber = firstNumber < SecondNumber; // false
Enter fullscreen mode Exit fullscreen mode
  • >

Operation "more than". Compares two operands and returns true if the first operands is greater than the second, otherwise returns false:

int firstNumber = 10;
int secondNumber = 4;
bool thirdNumber = firstNumber > secondNumber; // true
Enter fullscreen mode Exit fullscreen mode
  • <=

Operation "greater than or equal to." Compares two operands and returns true if the first operand is greater than or equal to the second, otherwise false is returned:

int firstNumber = 10;
int secondNumber = 4;
bool thirdNumber = firstNumber <= secondNumber; // false
bool fourthNumber = firstNumber <= 10; // true
Enter fullscreen mode Exit fullscreen mode
  • >=

Operation "greater than or equal to." Compares two operands and returns true if the first operand is greater than or equal to the second, otherwise false is returned:

int firstNumber = 10;
int secondNumber = 10;
bool thirdNumber = firstNumber >= secondNumber;     // true
bool fourthNumber = firstNumber >= 25;    // false
Enter fullscreen mode Exit fullscreen mode

Logical operators

&& - Logical operator AND
|| - Logical OR operator
! - Unary logical negation

bool firstCondition = true;
bool secondCondition = false;

bool firstResult = firstCondition && secondCondition // false
bool secondResult = firstCondition || secondCondition // true
bool thirdResult = !firstCondition // false
Enter fullscreen mode Exit fullscreen mode

My GitHub

References:
1.Microsoft

Top comments (0)