Is there a concise way to loop over true/false in C#?
I have ~20 lines of code in a unit test I'd rather not duplicate to toggle one boolean true/false.
I could break it off into a function and call it twice, but meh. This code feels more like I'm iterating over possible values than performing a distinct action with different parameters. Even if I had a function, I'd prefer the syntax of looping over the possible values rather than just calling it twice.
I could write a for
loop like so...
bool toggle;
for (int i = 0; i < 2; i++)
{
toggle = i == 1;
}
But that doesn't seem very clean.
I like this syntax:
for (bool b : { false, true }) { /* ... */ }
But it doesn't look like that will compile in C#.
Edit:
Following Jeroen's suggestion about local functions and Dmitry's answer, this is the route I went:
[TestMethod]
public void GetAndSetValue()
{
foreach (bool toggle in new [] { false, true })
{
GetAndSetValue(toggle);
}
void GetAndSetValue(bool toggle)
{
// details not important
}
}
Reasonable coders can debate whether the loop reads more easily than two function calls:
GetAndSetValue(false);
GetAndSetValue(true);
I like the loop better, so I'll roll with it until someone complains. Cheers!
foreach (bool b in new bool[] { false, true }) {...}
– Latticeworknew[] { true, false }.ToList().ForEach(b => Console.WriteLine(b));
– WreathDoStuff(true)
andDoStuff(false)
looks a lot nicer than afor
loop. The cognitive load to parse out what the loop is doing is surely not worth the effort. – MosquitoI like the loop better, so I'll roll with it until someone complains.
- I am complaining so stop it. :) – Bornie