bool
, int
A bool
can be converted to 0 or 1. In other languages, false is equivalent to 0 and true is equivalent to 1. This is not possible in the C# language.
We convert bools to ints, first running through an example. We then test unsafe code in converting bools to ints. We benchmark to ensure our method is fast.
We cannot implicitly convert from bool
to int
. The C# compiler uses this rule to enforce program correctness. The same rule mandates you cannot test an int
in an if
-statement.
bool
into an int
with an implicit cast, you receive an error: "Can not convert type bool
to int."bool
into an int
(1 or 0).Convert.ToIn32
method to convert the bool
to an int
—no ternary is required.Convert.ToInt32
up in IL Disassembler, I found it performs the same logic as the ternary (it branches).using System; // Version 1: convert bool to int. bool testBool = true; int testInt = testBool ? 1 : 0; Console.WriteLine("TEST BOOL: " + testBool); Console.WriteLine("TEST INT: " + testInt); // Version 2: also convert bool to int. bool testBool2 = false; int testInt2 = Convert.ToInt32(testBool2); Console.WriteLine("TEST BOOL 2: " + testBool2); Console.WriteLine("TEST INT 2: " + testInt2);TEST BOOL: True TEST INT: 1 TEST BOOL 2: False TEST INT 2: 0
I benchmarked the 2 statements and found identical performance. The compiler efficiently inlines Convert.ToInt32
to be the same as the ternary expression.
bool
to an int
(either 0 or 1).Convert.ToIn32
method to convert the bool
to an int
. Its results are identical.using System; using System.Diagnostics; const int _max = 100000000; var s1 = Stopwatch.StartNew(); // Version 1: use ternary. for (int i = 0; i < _max; i++) { bool testBool = true; int testInt = testBool ? 1 : 0; if (testInt != 1) { return; } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use Convert.ToInt32. for (int i = 0; i < _max; i++) { bool testBool = true; int testInt = Convert.ToInt32(testBool); if (testInt != 1) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));0.27 ns Use ternary 0.27 ns Use Convert.ToInt32
There are other ways to convert bools to ints, including unsafe code with casts, and StructLayout
-based approaches. These tend to be slower, and not worth the trouble.
Use a ternary or if
-statement to convert from bool
to int
. I suggest that the ternary statement is best, as it involves the fewest characters to type and is simple.