TOC

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

Data types:

Booleans

A bool (logikai) adattípus a .NET framework egyik legegyszerűbb adattípusa, mivel csak két lehetséges értékkel rendelkezik: igaz vagy hamis. A boolean változót így hozhatja létre:

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;

Amikor logikai értékkel dolgozunk, általában ellenőrizzük annak jelenlegi állapotát, majd reagálunk rá, például egy if parancs használatával:

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.

Típus átalakítás

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());

Összegzés

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!