TOC

This article is currently in the process of being translated into Spanish (~19% done).

Data types:

Booleans

El tipo de dato bool es uno de los mas simples que se encuentran en el framework .NET, porque solo tiene dos posibles valores: falso o verdadero. Puedes declarar una variable booleana de la siguiente forma :

bool isAdult;

Por defecto, el valor de un bool es falso, pero puedes por supuesto cambiar eso, ya sea cuando declares la variable o más adelante:

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!