Switch Statment

mp3909

Well-known member
Joined
Apr 22, 2018
Messages
61
Location
UK
Programming Experience
3-5
Hello,

I am new to C# and currently learning.
I was hoping someone can assist me with the below as I am getting an error saying Invalid expression term '>' and Invalid expression term '<'.

C#:
using System;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter a number");
        bool result;
        result = int.TryParse(Console.ReadLine(), out int x);
        if(result == true)
        {
            switch(x)
            {
                case > 10:
                    Console.WriteLine("Your number is {0} is bigger than 10", x);
                    break;
                case < 10:
                    Console.WriteLine("Your number is {0} is smaller than 10", x);
                    break;
                default:
                    Console.WriteLine("Your number is equal to 10");
                    break;
            }
        }


Thank You.
 
Use if-else instead, switch cases is for constant values.
 
You could do what you want in VB with a Select Case statement, which is a more functional analogue of the C# 'switch' statement:
C#:
Dim x As Integer

'...

Select Case x
    Case Is < 10
        '...
    Case Is > 10
        '...
    Case Else
        '...
End Select
C# follows more closely the more limited rules of the C/C++ switch statement though. What that does mean is that you can group cases so, if you have a limited number, you could do something like this:
int x;

// ...

switch (x)
{
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
        // ...
        break;
    case 10:
        // ...
        break;
    default:
        // ...
        break;
}

In your case though, there's nothing to stop the user entering a negative number so this sort of thing is not possible. Even if the user was limited to positive or non-negative numbers though, that syntax does noticeably improve performance and it's probably harder to read so the 'if...else' is probably a better bet anyway.
 
Back
Top Bottom