Thanks to cechode for inspiring this tip/trick. Suppose you have the following functions:
bool Step1()
{
return true;
}
bool Step2(int val1, int val2)
{
return val1 == val2;
}
bool Step3()
{
MessageBox.Show("I will be reached.");
return false;
}
bool Step4()
{
throw new Exception("This should be impossible!");
}
Function Step1() As Boolean
Return True
End Function
Function Step2(ByVal val1 As Integer, ByVal val2 As Integer) As Boolean
Return val1 = val2
End Function
Function Step3() As Boolean
MessageBox.Show("I will be reached.")
Return False
End Function
Function Step4() As Boolean
Throw New Exception("This should be impossible!")
End Function
If you want to execute each of those in sequence until one returns false
, you can do the following:
new Func<bool>[]
{
Step1,
() => Step2(1, 1),
Step3,
Step4,
() => 0 == 1
}.Any((step) => !step());
Select Case False
Case Step1()
Case Step2(1, 1)
Case Step3()
Case Step4()
Case 0 = 1
End Select
Note that the result need not be true
or false
; it can be any value or condition. I could, for example, process each function until the result is an integer greater than or equal to 5
(Note that in VB.NET the Select Case
statement can't handle conditions, it can
only handle values, so the code is modified accordingly):
new Func<int>[]
{
Step1,
() => Step2(1, 1),
Step3,
Step4,
() => 0 + 1
}.Any((step) => step() >= 5);
Dim steps() As Func(Of Integer) =
{
AddressOf Step1,
Function() Step2(1, 1),
AddressOf Step3,
AddressOf Step4,
Function() 0 + 1
}
steps.Any(Function([step]) [step]() >= 5)
The condition >= 5
is a very short one, so this won't save you any typing over
the short-circuiting technique shown below. However, it would save you some typing for longer conditions.
Specifying the condition only once rather than for each value also reduces the probability that you will
make a mistake when typing. And if you change the condition later on, you only have to change the condition
in one place rather than many. Here is the short-circuiting approach, which leads to duplicated code:
if (Step1() >= 5 ||
Step2(1, 1) >= 5 ||
Step3() >= 5 ||
Step4() >= 5 ||
0 + 1 >= 5)
{ }
If Step1() >= 5 OrElse
Step2(1, 1) >= 5 OrElse
Step3() >= 5 OrElse
Step4() >= 5 OrElse
0 + 1 >= 5 Then
End If
While shorter for this example (due to the short condition), this code also has the maintenance
problems and higher probability of human error explained above.