Complex Boolean Logic
Part of the Logic & Flow section of Coddy's C# journey — lesson 9 of 66.
Boolean logic can become complex when combining multiple conditions. Understanding operator precedence and using parentheses helps write clear, correct expressions.
The order of precedence for boolean operators in C# is:
- NOT (!)
- AND (&&)
- OR (||)
Here's an example of a complex boolean expression:
bool isValid = age >= 18 && (score > 70 || hasPriorExperience) && !isBlacklisted;Use De Morgan's Laws to simplify complex negations:
// Instead of:
if (!(age >= 18 && score > 70))
{
// This is equivalent to:
if (age < 18 || score <= 70)
{
Console.WriteLine("Not eligible");
}
}Short-circuit evaluation: With && and ||, C# evaluates only what's necessary:
// If user is null, C# won't evaluate the second condition
if (user != null && user.IsActive)
{
Console.WriteLine("Active user");
}Use explicit parentheses for clarity, even when not strictly required:
bool result = (isWeekend || isHoliday) && (hour > 10 && hour < 20);Challenge
MediumCreate a method called determineAccess that determines if a user has access to a system based on these rules:
- Takes five parameters:
- isAdmin (bool): Whether the user is an administrator
- isLoggedIn (bool): Whether the user is currently logged in
- timeOfDay (int): The current hour (0-23)
- isMaintenanceMode (bool): Whether the system is in maintenance mode
- hasEmergencyAccess (bool): Whether the user has emergency access
- Returns true when ANY of these conditions are true:
- The user is an admin AND is logged in
- The time is between business hours (9-17 inclusive) AND the user is logged in AND the system is NOT in maintenance mode
- The user has emergency access
Cheat sheet
Boolean operator precedence in C# (highest to lowest):
- NOT (!)
- AND (&&)
- OR (||)
Complex boolean expressions:
bool isValid = age >= 18 && (score > 70 || hasPriorExperience) && !isBlacklisted;De Morgan's Laws for simplifying negations:
// Instead of:
if (!(age >= 18 && score > 70))
{
// This is equivalent to:
if (age < 18 || score <= 70)
{
Console.WriteLine("Not eligible");
}
}Short-circuit evaluation prevents errors by evaluating only what's necessary:
// If user is null, C# won't evaluate the second condition
if (user != null && user.IsActive)
{
Console.WriteLine("Active user");
}Use explicit parentheses for clarity:
bool result = (isWeekend || isHoliday) && (hour > 10 && hour < 20);Try it yourself
public class DetermineAccess
{
// Implement the determineAccess method
public static bool determineAccess(bool isAdmin, bool isLoggedIn, int timeOfDay, bool isMaintenanceMode, bool hasEmergencyAccess)
{
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety