Add a additional condition to Case Statement in Switch
You can't add condition to a case. Case clause has to be a compile time constant. Instead you can use an if statement inside the case statement.
case 3:
if( > 2012)
{
//Do Something here..........
}
break;
The answer is no.
You'll need the following:
switch (MyEnum)
{
case 1:
case 2:
DoSomething();
break;
case 3:
if (Year > 2012) DoSomething();
break;
}
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;
}
In order for it to work the way you've indicated with the fallthrough logic for 1 and 2, I'd suggest moving the //do something here
portion out to a method or function and then doing this:
case 1:
case 2:
DoSomething();
break;
case 3:
if(Year > 2012) { DoSomething(); }
break;
The other alternative would be:
case 1:
case 2:
case 3:
if (MyEnum != 3 || Year > 2012) {
// Do something here
}
break;
but I think the first option is much more intuitive and readable.