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

Relational patterns in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Relational patterns help you check if a value is less than, greater than, or equal to another value in a simple way.

When you want to check if a number is bigger or smaller than another number.
When you want to run different code depending on a value's size.
When you want to make your code easier to read by using clear comparisons.
When you want to use pattern matching with conditions in a switch or if statement.
Syntax
C Sharp (C#)
value is < constant
value is <= constant
value is > constant
value is >= constant

Relational patterns are used with the is keyword in C#.

You can use them inside switch statements or if statements.

Examples
This checks if number is greater than 5 and prints a message if true.
C Sharp (C#)
int number = 10;
if (number is > 5)
{
    Console.WriteLine("Number is greater than 5");
}
This uses relational patterns in a switch to print age groups.
C Sharp (C#)
int age = 18;
switch (age)
{
    case < 13:
        Console.WriteLine("Child");
        break;
    case >= 13 and < 20:
        Console.WriteLine("Teenager");
        break;
    default:
        Console.WriteLine("Adult");
        break;
}
Sample Program

This program checks the temperature and prints a message based on its value using relational patterns.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int temperature = 30;

        if (temperature is < 0)
        {
            Console.WriteLine("Freezing cold");
        }
        else if (temperature is >= 0 and < 20)
        {
            Console.WriteLine("Cool weather");
        }
        else if (temperature is >= 20 and < 30)
        {
            Console.WriteLine("Warm weather");
        }
        else
        {
            Console.WriteLine("Hot weather");
        }
    }
}
OutputSuccess
Important Notes

You can combine relational patterns with and and or for more complex checks.

Relational patterns make your code easier to read compared to using multiple comparison operators.

Summary

Relational patterns let you compare values simply inside is expressions.

They work well in if statements and switch cases.

Use them to write clear and readable conditions based on value comparisons.