find and solve || findandsolve.com
Please wait.....

Booleans in C#

In programming, we need data type that can have only one of the following values:

YES/NO, ON/OFF, TRUE/FALSE

For this , C# has a bool data type, which can take the values true or false. A Boolean type is declared with the bool keyword.

Example
bool  isColdWeather = true;
bool isWarm = false;
Console.WriteLine( isColdWeather);// Outputs True
Console.WriteLine( isWarm);// Outputs False

A Boolean expression is a C# expression that returns a Boolean value: True or False.

We can use the comparison operator, such as greater than(>) operator to find out if an expression ( or a variable) is true:

Example
int  x  = 9;
int y = 8;
Console.WriteLine(x > y); // returns True, because 9 is greater than 8
//Even Easier:
Console.WriteLine(9 > 8); // returns True, because 9 is greater than 8

Boolean value mustly use to checking it's current state and then reacting to it. For example using if statement like as given below.

bool isChecked= true;  

if (isChecked)
//or also you can use if statment as given below
 //if (isAdult == true)
    Console.WriteLine("An  Checked");
else
    Console.WriteLine("This is not   Checked");


Type conversion

It's not very often that you will find the need to convert a boolean into another type using Convert.ToBoolean, because it's so simple. We need to convert between an integer and a boolean because booleans are sometimes represented as either 0 (false) or 1 (true).

int intVal= 1;
bool isChecked = Convert.ToBoolean(intVal);
Console.WriteLine("Bool: " + isChecked.ToString());
Console.WriteLine("Int: " + Convert.ToInt32(isChecked).ToString());