.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple Window

Convert 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.Bool

Note:When you try to convert a bool into an int with an implicit cast, you receive an error: "Cannot convert type bool to int."

Compile-Time Error
Based on: .NET 4.5
Example. First, you 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 integer in an if-statement. Here we correctly convert from bool to int.

Note:I felt there had to be some way to cast the true into a 1, and the false into a 0. But this is not possible.

C# program that uses bools

using System;

class Program
    static void Main()
	// Example bool is true.
	bool t = true;

	// A.
	// Convert bool to int.
	int i = t ? 1 : 0;
	Console.WriteLine(i); // 1

	// Example bool is false.
	bool f = false;

	// B.
	// Convert bool to int.
	int y = Convert.ToInt32(f);
	Console.WriteLine(y); // 0


You cannot cast bool to int, such as in the statement (int)true, without a compiler error. Opening up Convert.ToInt32 up in IL Disassembler, I found it tests the bool parameter against true and returns 1 if it is true, or false otherwise.Convert.ToInt32 Method: MSDN
Further, I benchmarked the two statements (A, B) and found identical performance. The compiler efficiently inlines Convert.ToInt32(bool) to be the same as the ternary expression in A. Therefore, A and B follow the same instructions.

Note:There is more information about the ternary operator on this site. It is useful for small conditional statements.

Ternary Operator
Summary. Here we saw that you must use a ternary or if-statement to convert from bool to int. I suggest that the ternary statement above is best, as it involves the fewest characters to type and is simple.

Also:Extension methods could solve this problem partly, but they would make most projects more complex.

Extension Method