Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Switch Between Two Numbers?

I am trying to make an intelligent switch statement instead of using 20+ if statements. I tried this

private int num;
switch(num)
{
    case 1-10:
        Return "number is 1 through 10"
        break;
    default:
        Return "number is not 1 through 10"
}

It says cases cannot fall through each other.

Thanks for any help!

like image 939
nathan Avatar asked Oct 18 '25 20:10

nathan


1 Answers

With recent changes introduced in C# 7, it is now possible to switch on a range.

Example:

int i = 63;

switch (i)
{
    case int n when (n >= 10):
    Console.WriteLine($"I am 10 or above: {n}");
    break;

    case int n when (n < 10 && n >= 5 ):
    Console.WriteLine($"I am between 10 and 5: {n}");
    break;

    case int n when (n < 5):
    Console.WriteLine($"I am less than 5: {n}");
    break;
}

Note: This really doesn't help the OP much, but hopefully it will help someone looking for this in the future.

like image 125
Steve Gomez Avatar answered Oct 20 '25 09:10

Steve Gomez