TOC

The community is working on translating this tutorial into Vietnamese, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Data types:

Booleans

The bool (boolean) data type is one of the simplest found in the .NET framework, because it only has two possible values: false or true. You can declare a boolean variable like this:

bool isAdult;

By default, the value of a bool is false, but you can of course change that - either when you declare the variable or later on:

bool isAdult = true;

Working with a boolean value usually means checking its current state and then reacting to it, e.g using an if-statement:

bool isAdult = true;  
if (isAdult == true)  
    Console.WriteLine("An adult");  
else  
    Console.WriteLine("A child");

But actually, it can be done a bit shorter, because when you check a boolean value, you can omit the true part - C# will understand this example in the exact same way:

bool isAdult = true;  
if (isAdult)  
    Console.WriteLine("An adult");  
else  
    Console.WriteLine("A child");

Whether you use the explicit approach or not is usually just a matter of taste. You can of course check for false as well - either by switching the keyword true with the keyword false, or by negating the variable with the exclamation mark operator:

bool isAdult = true;  
if (!isAdult)  
    Console.WriteLine("NOT an adult");  
else  
    Console.WriteLine("An adult");

The if-statement now basically asks "is the variable isAdult the opposite of true?", thanks to the exclamation mark which is also known as the logical negation operator.

Type conversion

It's not very often that you will find the need to convert a boolean into another type, because it's so simple. However, you may need to convert between an integer and a boolean because booleans are sometimes represented as either 0 (false) or 1 (true). For this purpose, I recommend the built-in Convert class, which can help you with most conversion tasks. Simply use the ToBoolean() method to convert an integer to a boolean, and the ToInt32() method if you want to go the other way. Here's an example:

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

Summary

The bool data type can only have two values - false or true. It's easy to check with an if statement and is often the return type of many methods.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!