TOC

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

Data types:

Booleans

Zmienna typu bool (boolean) to jedna z najprostszych zmiennych na platformie .NET, ponieważ posiada tylko dwie możliwe wartości: false (fałsz) oraz true (prawda). Możesz zadeklarować zmienną boolean tak:

bool isAdult;

Domyślnie, zmienna bool ma wartość false. Oczywiście można ją zmienić - przy deklaracji zmiennej lub w późniejszym czasie:

bool isAdult = true;

Praca z wartością logiczną boolean zwykle oznacza sprawdzenie jej aktualnego stanu, a następnie zareagowanie na niego, np. za pomocą instrukcji if:

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

W rzeczywistości można to napisać krócej, ponieważ sprawdzając wartość logiczną, można pominąć część prawdziwą - C# zrozumie ten przykład dokładnie tak samo:

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

Instrukcja warunkowa if po prostu sprawdza "czy zmienna isAdult jest równa przeciwieństwu prawdy (zaprzeczeniu)", dzięki znakowi wykrzyknika, który jest również znany jako operator negacji.

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

Typ danych boolmoże mieć tylko dwa stany - prawdę (true) i fałsz (false). Łatwo to sprawdzić za pomocą instrukcji warunkowej if i jest często typem zwracanym przez wiele metod.


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!