C# Logical Operators

C# Logical Operators
Logical operators in C# are used to combine boolean expressions and produce a single boolean result. They are essential for making complex decisions within your code.
Types of Logical Operators:
 * Logical AND (&&)
   * Returns true if both operands are true.
   * Returns false otherwise.
   bool isSunny = true;
bool isWarm = true;

if (isSunny && isWarm)
{
    Console.WriteLine("It's a perfect day for a picnic!");
}

 * Logical OR (||)
   * Returns true if at least one operand is true.
   * Returns false if both operands are false.
   bool hasMoney = false;
bool hasCreditCard = true;

if (hasMoney || hasCreditCard)
{
    Console.WriteLine("You can make a purchase.");
}

 * Logical NOT (!)
   * Reverses the logical state of its operand.
   * Returns true if the operand is false.
   * Returns false if the operand is true.
   bool isRaining = false;

if (!isRaining)
{
    Console.WriteLine("Let's go outside!");
}

Short-Circuit Evaluation:
C# uses short-circuit evaluation for && and || operators. This means that the second operand is only evaluated if the result of the expression can't be determined from the first operand.
 * &&: If the first operand is false, the entire expression is false, and the second operand is not evaluated.
 * ||: If the first operand is true, the entire expression is true, and the second operand is not evaluated.
Example:
int x = 10;
int y = 0;

if (x > 5 && y / x > 2)
{
    // This code will not execute because the first condition (x > 5) is true,
    // but the second condition (y / x > 2) would result in a division by zero error.
    Console.WriteLine("This will not be printed.");
}

By understanding these logical operators and their behavior, you can create more complex and efficient decision-making logic in your C# programs.

Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Kotlin Strings: Features and Operations Guide

Kotlin Android Program (QCR) Application Codes That Read Text in Photos