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?
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?
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;
}
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.