C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
This is not possible in the C# language. We convert bools to ints, first running through an example.
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."
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 } } Output 1 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.
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.
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.