TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Bool Type: If True, False

These C# examples test the bool type, which holds true or false. A bool occupies 1 byte of memory.

Bool stores true or false.

It is often used in expressions. Bool variables can be assigned values based on expressions. Many expressions evaluate to a boolean value. Represented in one byte, the bool type represents truth.

Intro. First, a bool can be assigned to the true and false literals. In this program, we set the bool variable to true. And then we invert the value of the bool using the exclamation operator.

True, False

Info: The word bool comes from George Boole, a mathematician who pioneered Boolean logic in the 1800s in England.

Based on:

.NET 4.5

C# program that uses bool

using System;

class Program
{
    static void Main()
    {
	bool val = true;
	if (val)
	{
	    Console.WriteLine(val == true);
	}
	val = !val;
	if (!val)
	{
	    Console.WriteLine(val == false);
	}
    }
}

Output

True
True

Example 2. Next, this program declares a bool variable. It manipulates its values through expressions and also evaluates its value. The size of the bool type is one byte. It is aliased to the System.Boolean type.

C# program that uses bool in many contexts

using System;

class Program
{
    static void Main()
    {
	// Use a local variable of type bool.
	// ... Write its value.
	// ... Then invert its value with unary not.
	// ... Then set to false.
	bool value = true;
	Console.WriteLine(value);

	value = !value;
	Console.WriteLine(value);

	value = false;
	Console.WriteLine(value);

	// You can test the boolean value in an if-statement.
	// ... Only the second if-statement body is reached.
	if (value)
	{
	    Console.WriteLine("Not reached");
	}
	if (!value)
	{
	    Console.WriteLine("Reached");
	}

	// You can use a bool local variable to store an expression result.
	// ... This simplifies some code.
	bool test = !value &&
	    1 == int.Parse("1");
	Console.WriteLine(test);

	// Print the bool size in bytes and its type.
	Console.WriteLine(sizeof(bool));
	Console.WriteLine(true.GetType());
    }
}

Output

True
False
False
Reached
True
1
System.Boolean

We see that the true and false literals are simply the hard-coded values true and false. These hard-coded values are called literals. True and false also have the TrueString and FalseString representations.

TrueString, FalseString

Invert boolean. The program's second assignment sets the variable value equal to its opposite value. This means that a true value will become a false value. This technique is useful for setting bool preferences.

Also: It is possible, but often not necessary, to define a custom Flip() method to do this.

Often, if-statements test an expression directly. But they can also test a bool variable storage location. In an if-statement, the expression is evaluated in a Boolean context. The bool variable is already stored in a Boolean context.

If

We can store the result of an expression evaluation as a local variable or field directly. This technique can simplify complex logic tests in your code. It can reduce the number of local variables, making the program's model simpler.

Usage. Bools can be used in a variety of program contexts to represent truth values. Because they are so common, it is good to see some examples of how they can be used. They are used throughout programs, even if you do not notice them.

bool.ParseBool ArraySort Bools

Methods: In C# programs, methods often return bool values. These methods sometimes have the prefix "Is" on their names.

Return Bool

Also: Properties can return bool values. The book Code Complete shows how boolean expressions are simplified.

Int to bool. Ints and bools are both value types. How can you convert an int in your C# program to a bool value? This can be done with the Convert.ToBoolean method in the System namespace. A custom method could also be used.

IntBool to Int

This program uses the Convert type to convert ints into bools. The Convert.ToBoolean method is perfect for this purpose. This method considers 0 to be false. All other values, positive and negative, are true.

C# program that converts int to bool

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(Convert.ToBoolean(5));
	Console.WriteLine(Convert.ToBoolean(0));
	Console.WriteLine(Convert.ToBoolean(-1));
    }
}

Output

True
False
True

Research. I learned some technical specifics of bool in the CLI specification. If the byte has all zeros, it means false. And if any of the four bits in that byte are set to 1, it is true. Here is the quote from the specification.

A CLI Boolean type occupies 1 byte in memory. A bit pattern of all zeros denotes a value of false. A bit pattern with any bit set (analogous to a non-zero integer) denotes a value of true.

The CLI Annotated Standard

Summary. Nearly every C# program uses bools. All if-statements requires a boolean expression. We explored bools, established its representation size in bytes, and tested conversions to bools.

Often: Bools are used as intermediate storage locations for expression evaluations. They reduce complexity in complex conditional logic.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf