C# Conditionals

C# Conditionals

Learn about logic expressions, boolean, branching and selection in C#

Here is an explanation of logic, boolean values and operators in C#: Logic involves the use of boolean values and operators to represent conditions and make decisions.

Boolean values - There are two boolean values in C#:

  • true

  • false

Boolean variables can only hold one of these two values. They are used to represent conditions that are either true or false.

Boolean operators - There are three main boolean operators in C#:

  • && - AND operator. Returns true if both operands are true.

  • || - OR operator. Returns true if either operand is true.

  • ! - NOT operator. Inverts the operand (true becomes false and vice versa).

For example:

bool isRaining = true;
bool isWeekend = false;

bool canGoOut = !isRaining && isWeekend;
// canGoOut will be false

bool hasUmbrella = true;

bool willGoOut = canGoOut || hasUmbrella;  
// willGoOut will be true

The boolean operators allow you to combine multiple conditions using logic.


Decision

The decision statement in C# is the if statement. It allows you to conditionally execute a block of code based on some condition.

The basic syntax (branching)

if (condition) { // code block to execute if condition is true
}

You can have an optional else block to execute if the condition is false (forking):

if (condition) { 
   // code block
} else { 
   // else block
}

For example:

int a = 10;
if (a > 5) 
{
    Console.WriteLine("a is greater than 5"); 
}
else  
{
    Console.WriteLine("a is not greater than 5");
}

You can also have else if blocks to check for multiple conditions (conditional selector also known as ladder):

int a = 10;  
if (a > 5)  
{
    Console.WriteLine("a is greater than 5");
}  
else if (a < 5)
{
    Console.WriteLine("a is less than 5"); 
}
else  
{
    Console.WriteLine("a is equal to 5");
}

The if statement allows you to execute code conditionally based on boolean expressions, making it a fundamental part of conditional programming in C#.


Ternary Operator

The ternary operator is a shortcut syntax for an if-else statement in C#. It allows you to assign a value to a variable based on a condition in one line.

The basic syntax is:

condition ? valueIfTrue : valueIfFalse;

For example:

int a = 10;
int result = a > 5 ? 100 : 200;

Here, the result will be assigned 100 if a > 5 is true, otherwise 200.

This is equivalent to the if-else statement:

if (a > 5)  
{
    int result = 100;  
}
else  
{
    int result = 200;
}

The ternary operator is useful when you want to assign a value to a variable based on a simple condition in a concise one-line statement.

You can also assign to variables of any type, not just int:

string result = a > 5 ? "Greater" : "Less";

However, the ternary operator should be used sparingly to avoid reducing readability. If statements are more explicit and self-documenting in complex logic.

The ternary operator provides an alternative, more concise syntax to a simple if-else statement in C#. But for complex conditions, if statements are more readable.


Optimization

Logic expression optimization is the process of simplifying complex boolean expressions to make them more efficient and readable. This can be done by applying logic rules and identities to reduce the number of operations.

Some common optimization techniques in C# are:

  1. Removing redundant expressions:
// Before
if (a > 0 && a > 0)

// After 
if (a > 0)
  1. Applying De Morgan's laws:
// Before
if (!(a > 0) || !(b < 10))

// After  
if (a <= 0 || b >= 10)
  1. Removing double negations:
// Before
if (!(!a))

// After
if (a)
  1. Factoring common terms:
// Before
if (a > 0 && b > 0)  
if (a > 0 && c > 0)

// After  
if (a > 0 && (b > 0 || c > 0))

For example:

if ((a > 0 && b > 0) || (!(a > 0) && c > 0))
{
    // ...
}

Can be optimized to:

if ((a > 0 && b > 0) || (a <= 0 && c > 0))    
{
    // ...
}

In summary, logic expression optimization in C# involves applying logic rules and identities to simplify boolean expressions. This can improve the performance and readability of your code.


Short Circuit

Performance improvement for OR statements by ordering conditions from most probable to least probable can be achieved due to short-circuit evaluation.

In short-circuit evaluation, the compiler evaluates conditions from left to right and stops (or "short-circuits") as soon as the result is known. This means that if the first condition is true, the second condition is not evaluated at all.

For an OR (||) statement, if the first condition is true, the whole OR statement is true, so the second condition does not need to be evaluated.

So by ordering conditions from most probable to least probable, you maximize the chances that the first condition is true and short-circuiting can occur, skipping evaluation of the second condition.

For example:

if (a > 0 || b > 10) 
{
   ...
}

Here, assuming a > 0 is more probable than b > 10, we reorder the conditions:

if (a > 0 || b > 10)      // Less efficient

if (b > 10 || a > 0)      // More efficient

Now, if a > 0 is true, the second condition b > 10 is never evaluated, resulting in better performance.

In summary, by ordering OR conditions from most probable to least probable, you maximize the chances of short-circuit evaluation occurring and skip evaluation of the latter conditions, resulting in performance improvements.

The performance gains may be small for simple conditions but can be significant for complex boolean expressions especially if there is a function call for a second expression. So it is good practice to order OR conditions in this way for more optimized code.


Disclaim: This article is created with AI, but I have added a bit of value by explaining the optimization better. AI does not yet do a perfect job however I thunk is good enough for a beginner to learn the fundamentals.