Reputation: 9488
I have an array of booleans which gets filled by a loop. The method that owns the array needs to return a single boolean. So can I do this:
bool[] Booleans = new bool[4];
// do work - fill array
return (Booleans[0] && Booleans[1] && Booleans[2] && Booleans[3]);
So if I have: T,T,F,T
will I get F
back since there is one in the array or will it send back something else or just crash all together?
Upvotes: 1
Views: 1033
Reputation: 96507
A single false
will result in false
being returned with boolean AND
logic.
You can also rewrite as:
return Booleans.All(b => b);
For the sake of completeness, or if LINQ is not an option, you can achieve the same via a loop:
var list = new List<bool> { true, false, true };
bool result = true;
foreach (var item in list)
{
result &= item;
if (!item)
break;
}
Console.WriteLine(result);
For small samples what you have is fine, but as the number of items grow either of the above approaches will make the code a lot friendlier.
Upvotes: 14
Reputation: 41858
If you must process the array and return only a single boolean, then the best approach would be to just set a value to true, then loop through until the value is false, or you reach the end of the loop.
This way you won't have to process past the first false value, since that makes the entire result false.
How you loop through depends on which version of .NET you are using.
Upvotes: 0