0
0
C Sharp (C#)programming~5 mins

Logical patterns (and, or, not) in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Logical patterns help you check if things are true or false in a clear way. They let you combine conditions to make decisions in your program.

Checking if a user is both logged in and has permission before showing a page.
Deciding if a number is either less than 10 or greater than 100.
Making sure a password is not empty and contains special characters.
Skipping an action if a user is not active or not verified.
Syntax
C Sharp (C#)
case <pattern1> and <pattern2>:
    // code
case <pattern1> or <pattern2>:
    // code
case not <pattern>:
    // code

and means both patterns must match.

or means at least one pattern must match.

not means the pattern must NOT match.

Examples
This checks if number is greater than 10 and less than 20.
C Sharp (C#)
int number = 15;
switch (number)
{
    case > 10 and < 20:
        Console.WriteLine("Number is between 11 and 19");
        break;
}
This checks if letter is any vowel using or.
C Sharp (C#)
char letter = 'a';
switch (letter)
{
    case 'a' or 'e' or 'i' or 'o' or 'u':
        Console.WriteLine("Letter is a vowel");
        break;
}
This checks if isActive is NOT true.
C Sharp (C#)
bool isActive = false;
switch (isActive)
{
    case not true:
        Console.WriteLine("User is not active");
        break;
}
Sample Program

This program checks if a person can drive. They must be 18 or older and have a license. Otherwise, they cannot drive.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int age = 25;
        bool hasLicense = true;

        switch (age)
        {
            case >= 18 when hasLicense:
                Console.WriteLine("Can drive");
                break;
            case < 18:
                Console.WriteLine("Cannot drive");
                break;
            default:
                Console.WriteLine("Cannot drive");
                break;
        }
    }
}
OutputSuccess
Important Notes

Logical patterns work inside switch statements to make conditions easier to read.

The underscore _ means "anything" and is useful with when clauses.

Use parentheses if you want to group patterns for clarity.

Summary

Logical patterns combine conditions with and, or, and not.

They make your code easier to read and understand.

Use them inside switch to check complex conditions simply.