Thanks to @PeterDuniho for pointing out a way to make this work. The following code (while not as succinct and clean as the rust code) works in C# 7.
switch((i % 3 == 0, i % 5 == 0))
{
case ValueTuple<bool, bool> t when (t.Item1 == true && t.Item2 == true):
// FizzBuzz
break;
case ValueTuple<bool, bool> t when (t.Item1 == true && t.Item2 == false):
// Fizz
break;
case ValueTuple<bool, bool> t when (t.Item1 == false && t.Item2 == true):
// Buzz
break;
}
You could probably shorten the above even more by using logical shortcuts like this:
switch((i % 3 == 0, i % 5 == 0))
{
case ValueTuple<bool, bool> t when (t.Item1 && t.Item2):
// FizzBuzz
break;
case ValueTuple<bool, bool> t when (t.Item1):
// Fizz
break;
case ValueTuple<bool, bool> t when (t.Item2):
// Buzz
break;
}
This would work because it would only ever get to evaluate the second and third arguments if the previous one was false. Of course this only really works in a simple Boolean situation like this.
Also, i'd be wary about property evaluation here with side-effects. You shouldn't design properties to have side-effects, but if you do this might evaluate the properties multiple times, causing the side-effects to applied multiple times (ie, say your property adds or decrements a value each time it's called).
case
statement in aswitch
can be a type, with a variable declaration and awhen
clause to conditionally test for specific values. Unfortunately, the tuple syntax isn't recognized in that context, i.e. you can't writecase (bool, bool) t when...
, but instead have to writecase ValueTuple<bool, bool> t when...
. (Though oddly enough, you can writeswitch ((i % 3 == 0, i % 5 == 0))
). But otherwise, that approach would work here (though IMHO even if the tuple syntax was recognized in acase
, a dictionary would be more concise). – Forename