Meta Description:
Learn how to work with Boolean values and operators in C#. This guide covers relational and logical operators, including combining && (AND) and || (OR) for complex conditions, with easy-to-understand examples for making decisions in your code.
Before diving into conditions in C#, it’s essential to understand Boolean values and how they work. A Boolean value can either be true
or false
, and in C#, the primitive type to store Boolean values is bool
. There is also a Boolean
type in C#, but most of the time, the bool
keyword is used to create Boolean variables.
Boolean Variables and Relational Operators
We declare Boolean variables using the bool
keyword, and their values are set to true
or false
. But Boolean values become particularly useful when working with conditions. C# provides relational operators to compare values, such as checking if two values are equal, not equal, greater than, or less than. These comparisons return a Boolean value (true
or false
), which you can use to make decisions in your code.
Here’s a list of common relational operators in C#:
-
==
: Checks if two values are equal. -
!=
: Checks if two values are not equal. -
>
: Checks if one value is greater than another. -
<
: Checks if one value is less than another. -
>=
: Checks if one value is greater than or equal to another. -
<=
: Checks if one value is less than or equal to another.
Example 1: Using Relational Operators
Let’s say we want to check if a person’s age is equal to 30:
int age = 30;
// Check if the age is equal to 30
bool isThirty = age == 30;
Console.WriteLine("Is age 30: " + isThirty);
Explanation:
In this example, we use ==
to check if the age
is equal to 30
. If it is, isThirty
will be true
. Otherwise, it will be false
.
Now, let’s check if the age is greater than 30:
bool isGreaterThanThirty = age > 30;
Console.WriteLine("Is age greater than 30: " + isGreaterThanThirty);
Explanation:
Here, >
is used to check if the age is greater than 30. Since age
is 30, the result will be false
.
Logical Operators: Combining Conditions
C# also provides logical operators, which allow us to combine multiple conditions:
-
&&
: Logical AND – Returnstrue
if both conditions are true. -
||
: Logical OR – Returnstrue
if either condition is true. -
!
: Logical NOT – Reverses the result of a Boolean expression.
Example 2: Using Logical AND (&&
)
Let’s say we want to check if an age is between 18 and 65:
int personAge = 35;
// Check if the age is between 18 and 65
bool isValidAge = (personAge >= 18) && (personAge <= 65);
Console.WriteLine("Is age between 18 and 65: " + isValidAge);
Explanation:
In this example, &&
ensures that both conditions (age greater than or equal to 18, and age less than or equal to 65) are true. If both are true, isValidAge
will be true
.
Example 3: Using Logical OR (||
)
Now, let’s check if either one of two conditions is true:
int personAge1 = 17;
int personAge2 = 40;
// Check if either personAge1 is greater than 18 or personAge2 is less than 65
bool isEitherConditionTrue = (personAge1 >= 18) || (personAge2 <= 65);
Console.WriteLine("Is either condition true: " + isEitherConditionTrue);
Explanation:
The ||
operator checks if either one of the two conditions is true. In this case, since personAge1
is not greater than 18 but personAge2
is less than 65, the result is true
.
Combining Relational and Logical Operators
You can combine relational and logical operators to create more complex conditions.
Example 4: A Complex Check with AND and OR
Let’s check if age1
is greater than or equal to 18 and age2
is less than 65, or if either condition alone is true:
int age1 = 20;
int age2 = 70;
// Logical AND (both conditions must be true)
bool areBothAgesValid = (age1 >= 18) && (age2 <= 65);
Console.WriteLine("Are both ages valid: " + areBothAgesValid);
// Logical OR (either condition can be true)
bool isEitherAgeValid = (age1 >= 18) || (age2 <= 65);
Console.WriteLine("Is either age valid: " + isEitherAgeValid);
Explanation:
- The
&&
operator ensures that bothage1
andage2
are valid (age1 must be 18 or older, and age2 must be 65 or younger). - The
||
operator checks if eitherage1
is valid (age 18 or older) orage2
is valid (age 65 or younger). Here’s an example that combines both&&
(Logical AND) and||
(Logical OR) operators in one condition:
Example: Combining &&
and ||
Let’s say you want to check if a person is eligible for a special offer. The person must either be older than 18 or have a VIP status, and at the same time, their purchase amount must be greater than or equal to $100.
int age = 17;
bool isVIP = true;
double purchaseAmount = 120.0;
// Check if the person is eligible for a special offer
bool isEligible = ((age > 18) || isVIP) && (purchaseAmount >= 100);
Console.WriteLine("Is the person eligible for the special offer: " + isEligible);
Explanation:
- The condition
(age > 18) || isVIP
checks if the person is either older than 18 or a VIP member. If either of these conditions is true, it will returntrue
. - The condition
(purchaseAmount >= 100)
checks if the purchase amount is greater than or equal to $100. - The
&&
operator ensures that both the purchase condition and one of the age or VIP conditions are true for the person to be eligible.
Result:
- In this case, since the person is not older than 18 but is a VIP and the purchase amount is $120 (greater than $100), the result will be
true
, meaning the person is eligible for the special offer.
Conclusion
Boolean values and operators are essential for making decisions in your C# programs. Relational operators let you compare values, while logical operators allow you to combine multiple conditions to create more complex expressions. These operators form the foundation for if-else statements and loops, making them a core concept to master.
With Boolean operators, you can write cleaner and more efficient code to handle decision-making in various scenarios. Keep practicing and combining these operators to gain a deeper understanding of how they work in C#!
Assignments for Boolean Values and Operators in C
Easy: Basic Boolean Operations
-
Check Even or Odd:
Write a program that checks whether a given number is even or odd.
Hint: Use the modulus operator
%
and compare it with0
.
int number = 25;
bool isEven = number % 2 == 0;
Console.WriteLine("Is the number even: " + isEven);
-
Age Eligibility Check:
Create a program to check if a person is eligible to vote. The voting age is 18 or older.
Input:
int age = 20;
Output:true
Medium: Combining Conditions
- Number Range Validation: Write a program to check if a number lies between 10 and 50, inclusive.
Example:
Input: int number = 25;
Output: true
Hint: Use the logical AND (&&
) operator.
bool isWithinRange = (number >= 10) && (number <= 50);
Console.WriteLine("Is the number in range: " + isWithinRange);
-
Check Admission Eligibility:
A student is eligible for admission if they score at least 80% in exams and have extracurricular participation.
Input:
-
double examScore = 85.0;
-
bool hasExtracurricularParticipation = true;
Output:true
-
Hint: Combine &&
for both conditions.
-
Weekend Check:
Write a program to check if a given day (string) is a weekend (Saturday or Sunday).
Input:
string day = "Sunday";
Output:true
Hint: Use the logical OR (||
) operator.
Difficult: Complex Conditions
-
Loan Eligibility Checker:
A person is eligible for a loan if:
- Their age is between 21 and 60.
- Their income is greater than or equal to $25,000.
- They have no existing loans.
Input:
-
int age = 30;
-
double income = 30000;
-
bool hasExistingLoans = false;
Output: true
Hint: Combine relational and logical operators.
-
Exclusive Event Access:
Write a program to check if a person qualifies for an exclusive event. The conditions are:
- They must either be a VIP or have purchased a ticket.
- They must be 18 years or older. Input:
-
bool isVIP = false;
-
bool hasTicket = true;
-
int age = 20;
Output:true
Hint: Use ||
for the first condition and &&
to combine it with the age check.
-
Retail Discount Eligibility:
A customer qualifies for a discount if:
- They are a loyalty member, or they spend at least $100.
- They have not returned items in the last 30 days. Input:
-
bool isLoyaltyMember = true;
-
double purchaseAmount = 80;
-
bool hasReturnedItems = false;
Output:true
Hint: Combine ||
and &&
operators effectively.
Bonus Challenge
Advanced Shopping Cart Validation:
Write a program for an online store to validate a shopping cart. The cart is valid if:
- The cart contains at least one item.
- The total amount is above $50.
- If a discount coupon is applied, the total amount after the discount must still exceed $30.
Input:
-
int itemsInCart = 3;
-
double totalAmount = 60;
-
bool hasDiscountCoupon = true;
-
double discountAmount = 20;
Output: true
How to Use These Assignments:
- Encourage Implementation: Provide the problem statement and hints but avoid giving complete solutions initially.
- Explain Edge Cases: For example, in the "Weekend Check," explain what happens if input is in lowercase (e.g., "sunday").
- Iterative Learning: Once assignments are completed, encourage readers to test different inputs and modify conditions to deepen their understanding.
These assignments cater to different skill levels, ensuring readers can progress at their own pace while mastering Boolean values and operators in C#.
Top comments (0)