-2

I prefer casting boolean value to integer, but I found using conditional operator ?: like in example:

boolVal ? 1 : 0;

I think it looks ridiculous. What is most efficient way to get numeric value from boolean value in .NET?

Bear
  • 1,017
  • 1
  • 10
  • 23
  • You only care about efficiency? – EpicKip Aug 22 '17 at 09:06
  • 3
    Why do you need the integer value instead of `true` or `false`? – Mighty Badaboom Aug 22 '17 at 09:06
  • bool f = true; int y = Convert.ToInt32(f); – pix Aug 22 '17 at 09:07
  • @pix read the first line, he knows how to cast its about speed – EpicKip Aug 22 '17 at 09:07
  • 1
    It's why it's only a comment and not an answer :) – pix Aug 22 '17 at 09:09
  • I'm aware of at least 5 ways to achieve same results. Also I'm aware that conditional operator ?: is sort of shorthand for if-else statement. I'm curious about *the best* solution and which more people prefer. That one quoted by me looks pretty bad. – Bear Aug 22 '17 at 09:11
  • 1
    Someone already ask how to convert bool to byte, maybe you can inspire yourself with this "tricks" to do it on integer: https://stackoverflow.com/questions/4980881/what-is-fastest-way-to-convert-bool-to-byte – pix Aug 22 '17 at 09:12
  • Both ternary operator & `Convert.ToInt32` are correct: https://stackoverflow.com/questions/8457366/c-sharp-boolean-int-conversion-issue (as alternatives: `if`, `switch` or any conditional statements). Seems it just a kind of casting readability instead performance. – Tetsuya Yamamoto Aug 22 '17 at 09:13
  • @Bear So it's not only about speed? – Mighty Badaboom Aug 22 '17 at 09:13
  • @MightyBadaboom It is, but readability also matters. Of course it's pretty easy to understand what happened there, but I mean code should be nice and most efficient. Purists versus Pragmatists... – Bear Aug 22 '17 at 09:19
  • @MightyBadaboom To me it seems more an aesthetic issue at hand, and he is asking what the "majority" of C# developer uses - no matter what solution they will most likely differ in nanoseconds (if even that) – Rand Random Aug 22 '17 at 09:20
  • This question is off topic here since there is no single right answer. I believe the ternary operator is "the most efficient" (or at least one of the ...), but either way "what people prefer" is opinion-based, so off topic. – Lasse V. Karlsen Aug 22 '17 at 09:34
  • Possible duplicate of [What is fastest way to convert bool to byte?](https://stackoverflow.com/questions/4980881/what-is-fastest-way-to-convert-bool-to-byte) – pix Aug 22 '17 at 09:37

2 Answers2

2

You could use Convert.ToInt32

int zeroOrOne = Convert.ToInt32(boolVal);

Use the most readable approach, performance will be the same.

This is the source code of Convert.ToInt32:

public static int ToInt32(bool value) {
    return value? Boolean.True: Boolean.False;
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • @EpicKip: you cannot cast a bool to int. What you could do is to cast it to `IConvertible` and then use `ToInt32` which is the same as above because it will call `Convert.ToInt32`. – Tim Schmelter Aug 22 '17 at 09:15
  • At the `return` it still uses ternary operator; same as OP has. Someone already found that both ternary & `Convert.ToInt32` follows same instructions: https://www.dotnetperls.com/convert-bool-int. – Tetsuya Yamamoto Aug 22 '17 at 09:17
  • @TetsuyaYamamoto: i have posted the .net code in my answer, you can see that it internally uses the conditional operator – Tim Schmelter Aug 22 '17 at 09:19
  • The updated source code, seemed odd at first sight - since I believed that ``Boolean.True`` is a ``bool`` and not an ``int``, naming is kinda missleading. TIL Microsoft guys are just as bad with naming stuff as I am. :) – Rand Random Aug 22 '17 at 09:27
  • @RandRandom: [`Boolean.True`](http://referencesource.microsoft.com/#mscorlib/system/boolean.cs,440a570fbff23b16,references) is an int. Well, it's `internal` – Tim Schmelter Aug 22 '17 at 09:34
  • ? Thanks for telling, but thats what I said... ``since I believed that Boolean.True is a bool and not an int`` - I ``believed`` it was a ``bool`` at first sight - I already know its an int, whats why I said ``naming is kinda missleading`` – Rand Random Aug 22 '17 at 09:37
1

I ran a quick test and comparing the conditional operator and Convert.ToInt32:

bool bVal = true;
Stopwatch sw = new Stopwatch();

sw.Start();
for(int i =0; i < amountOfTries; i++ )
{
    int b = bVal ? 1 : 0;
}
sw.Stop();
Console.WriteLine( $"Conditional operator: {sw.ElapsedTicks}t" );

sw.Restart();
for( int i = 0; i < amountOfTries; i++ )
{
    int b = Convert.ToInt32(bVal);
}
sw.Stop();
Console.WriteLine( $"Convert: {sw.ElapsedTicks}t" );

Result with 1000000 (1 million) tries:

Conditional operator: 7518 ticks
Convert: 8744 ticks

So the conditional operator is slightly faster in this case (its such a small difference the result can be different too). I think the Convert looks clearer personally though.

Note: As you can see in Tim Schmelter's answer, under the hood Convert.ToInt32(bool) does practically the same as the conditional operator.

EpicKip
  • 4,015
  • 1
  • 20
  • 37
  • It's really negligible. I have created a [`BenchMarkDotNet`](https://github.com/dotnet/BenchmarkDotNet) test which showed other results: `ConditonalOperator=299.3722 us` and `ToInt32=290.2959 us`, so `ToInt32` is even slightly faster. You have to compile in release mode and run without attached debugger – Tim Schmelter Aug 22 '17 at 09:40
  • @TimSchmelter That's why I added the footnote :), I couldn't repro ToInt32 being faster but I could remote the line that says its faster because it'd be false if you get different results – EpicKip Aug 22 '17 at 09:43
  • @Tim Schmelter: For those of us not familiar with such fine grained performance measurements does 299.3722 us = one third of one millisecond? – camelCase Aug 22 '17 at 09:45
  • @camelCase: it's microsecond(0.000001 sec), read [here](https://github.com/dotnet/BenchmarkDotNet/issues/459). Btw, my test also iterates 1million times – Tim Schmelter Aug 22 '17 at 10:02
  • @EpicKip, note that your test is somehow misleading, since you use always the same value (true) and that matters (look for "branch prediction" to understand why). With random values results are much slower, but, as expected, Convert and Conditional have similar timing. See it [here](https://dotnetfiddle.net/DkikU2) – Gian Paolo Aug 22 '17 at 10:27