I wrote a code in AS3 which allowed me to check if a particular number of things were true...
If (true + false + true + true + false + true + true < 4)
{
}
When i tried rewriting in C#, it tells me i cannot add type bool and bool. Is the best way of doing this to rewrite it like this? Or is there some simpler work around?
If ((true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) < 4)
{
}
You can combine two boolean values using the and operator, which looks like two ampersands: && . The and operator evaluates to true whenever the two boolean values on either side of it are also true .
To convert boolean to integer, let us first declare a variable of boolean primitive. boolean bool = true; Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”.
Because you can't add booleans, so it converts them to numbers first.
Bool data type in C++In C++, the data type bool has been introduced to hold a boolean value, true or false. The values true or false have been added as keywords in the C++ language.
Try using IEnumerable<T>.Count(Func<T,bool>)
from System.Linq
, with T
as bool
, on a params
method parameter.
public static int CountTrue(params bool[] args) { return args.Count(t => t); }
Usage
// The count will be 3 int count = CountTrue(false, true, false, true, true);
You can also introduce a this
extension method:
public static int TrueCount(this bool[] array) { return array.Count(t => t); }
Usage
// The count will be 3 int count = new bool[] { false, true, false, true, true }.TrueCount();
You could create an array and use Count
:
if ((new []{true, false, true, true, false, true, true}).Count(x=>x) < 4)
{
}
or the Sum
method:
if ((new []{true, false, true, true, false, true, true}).Sum(x=>x?1:0) < 4)
{
}
Here's a more fun example:
if ((BoolCount)true + false + true + true + false + true + true <= 5)
{
Console.WriteLine("yay");
}
Using this class:
struct BoolCount
{
private readonly int c;
private BoolCount(int c) { this.c = c; }
public static implicit operator BoolCount(bool b)
{ return new BoolCount(Convert.ToInt32(b)); }
public static implicit operator int(BoolCount me)
{ return me.c; }
public static BoolCount operator +(BoolCount me, BoolCount other)
{ return new BoolCount(me.c + other.c); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With