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

Constant patterns in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Constant patterns let you check if a value matches a fixed value easily. It helps you compare values in a clear way.

When you want to run code only if a variable equals a specific number or word.
When you use a switch statement and want to check for exact matches.
When you want to simplify if-else checks for fixed values.
When you want your code to be easier to read by clearly showing what values you expect.
Syntax
C Sharp (C#)
case constant_value:
    // code to run
    break;

The constant_value can be a number, string, or any fixed value.

This is often used inside switch statements or is expressions.

Examples
This checks if number is 5 or 10 and prints a message.
C Sharp (C#)
int number = 5;
switch (number)
{
    case 5:
        Console.WriteLine("Number is five.");
        break;
    case 10:
        Console.WriteLine("Number is ten.");
        break;
}
This uses a constant pattern to check if obj equals the string "hello".
C Sharp (C#)
object obj = "hello";
if (obj is "hello")
{
    Console.WriteLine("Greeting detected.");
}
Sample Program

This program uses constant patterns in a switch and an if statement to check fixed values and print messages.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int day = 3;
        switch (day)
        {
            case 1:
                Console.WriteLine("Monday");
                break;
            case 2:
                Console.WriteLine("Tuesday");
                break;
            case 3:
                Console.WriteLine("Wednesday");
                break;
            default:
                Console.WriteLine("Another day");
                break;
        }

        object greeting = "hello";
        if (greeting is "hello")
        {
            Console.WriteLine("We said hello!");
        }
    }
}
OutputSuccess
Important Notes

Constant patterns compare values exactly, so types must match or be compatible.

They make code easier to read compared to multiple if-else statements.

Summary

Constant patterns check if a value equals a fixed value.

They are often used in switch statements and is expressions.

They help write clear and simple code for exact value checks.