Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a additional condition to Case Statement in Switch

Is it possible to add a additional Condition to Switch Statement like below in C#

switch(MyEnum)
{ 
  case 1:
  case 2:
  case 3 && Year > 2012://Additional Condtion Here
       //Do Something here..........
      break; 
  case 4:
  case 5:
       //Do Something here..........
      break;  
 }

In above mentioned example if MyEnum = 3 then it has to be excuted if Year > 2012... Is it possible?

[EDITED]

Year > 2012 is not applicable to case 1 & case 2.

like image 799
andy Avatar asked Jan 10 '13 06:01

andy


People also ask

Can we add condition in switch-case?

If you want pass any value in switch statement and then apply condition on that passing value and evaluate statement then you have to write switch statement under an function and pass parameter in that function and then pass true in switch expression like the below example.

Can switch have multiple conditions?

To implement multiple conditions in a switch statement you have to write multiple case with conditions without a break; statement.

How do you add conditions to a switch-case in Java?

You can't do this in Java. A switch jumps to the case that matches the value you're switching on. You can't use expressions of age inside the case . However, you can use something called a "fallthrough" (see here and search for "fall through").

How do you add multiple statements to a switch-case?

Use break keyword to stop the execution and exit from the switch. Also, you can write multiple statements in a case without using curly braces { }. As per the above syntax, switch statement contains an expression or literal value. An expression will return a value when evaluated.


1 Answers

C#7 new feature:

case...when

https://docs.microsoft.com/hu-hu/dotnet/articles/csharp/whats-new/csharp-7

public static int DiceSum4(IEnumerable<object> values)
{
    var sum = 0;
    foreach (var item in values)
    {
        switch (item)
        {
            case 0:
                break;
            case int val:
                sum += val;
                break;
            case IEnumerable<object> subList when subList.Any():
                sum += DiceSum4(subList);
                break;
            case IEnumerable<object> subList:
                break;
            case null:
                break;
            default:
                throw new InvalidOperationException("unknown item type");
        }
    }
    return sum;
}
like image 59
eMeL Avatar answered Sep 21 '22 16:09

eMeL