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.
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.
To implement multiple conditions in a switch statement you have to write multiple case with conditions without a break; statement.
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").
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With