Return boolean elements in C # method

I have an array of boolean elements that is filled with a loop. The method to which the array belongs should return a single boolean value. 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 something else or just work together?

+1
arrays c #
source share
2 answers

One false will return false with the logical logic AND .

You can also rewrite it as:

 return Booleans.All(b => b); 

For completeness, or if LINQ is not an option, you can achieve the same through 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 good, but as the number of elements increases, one of the above methods will make the code more friendly.

+14
source share

If you have to process the array and return only one boolean, then the best approach would be to simply set the value to true and then loop until the value becomes false or you reach the end of the loop.

This way you do not have to handle the first false value, as this makes the whole result false.

How you go through the loop depends on which version of .NET you are using.

0
source share

All Articles