Convert bool to int in C#
This post will discuss how to convert bool to int in C#. The boolean value true is represented by 1, and false by 0.
1. Using Convert.ToInt32() method
Unlike C++, C# doesn’t support implicit conversion from type bool to int. The Convert.ToInt32() converts the specified value to the equivalent 32-bit signed integer. It is overloaded for all data types, including Boolean, and returns the integer 1 if the specified value is true; otherwise, 0.
The following example converts the boolean value true to 1 and boolean value false to 0 using Convert.ToInt32().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { bool b = true; int i = Convert.ToInt32(b); Console.WriteLine(i); // 1 b = false; i = Convert.ToInt32(b); Console.WriteLine(i); // 0 } } |
2. Using Custom method
We can also explicitly create an extension method to convert a boolean value to an integer. The following example provides an illustration.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; public static class Extensions { public static int ToInt(this bool value) { return value ? 1 : 0; } } public class Example { public static void Main() { bool b = true; int i = b.ToInt(); Console.WriteLine(i); // 1 b = false; i = b.ToInt(); Console.WriteLine(i); // 0 } } |
That’s all about converting bool to int in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)