rodo
rodo

Reputation: 29

Switch, Case, When

I saw an answer regarding the use of range of integers using "switch" and the condition "when" but I do not understand how it works, because it declares a new variable inside "case" and I do not know how it relates to the variable that is passed to switch to evaluate.

int i = 63;

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

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

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

Upvotes: 1

Views: 1027

Answers (1)

nick
nick

Reputation: 2853

In this case, n is simply another variable that holds the value of i. It might be more helpful to look at it another way with some pseudo code.

public abstract class Animal
{
     public abstract string Talk();
}

public class Dog : Animal
{
     public string Talk(){
         return "Bark";
     }
}


//cat class : Animal
//elephant class : Animal



Animal a = GetSomeRandomAnimal();


switch (a) {
    case Dog d:
        Console.WriteLine($"The dog says {d.Talk()}");
    case Cat c:
        Console.WriteLine($"The cat says {c.Talk()}");
     //etc
}

Here, the cases are checking to see if a is a Dog, or a Cat or any other cases that are specified. Hopefully that clears it up a little bit.

Upvotes: 4

Related Questions