Subscribe

RSS Feed (xml)

C# The bool Type

The bool type represents true/false values. C# defines the values true and false using the reserved words true and false. Thus, a variable or expression of type bool will be one of these two values. Unlike some other computer languages, in C# there is no conversion defined between bool and integer values. For example, 1 does not convert to true, and 0 does not convert to false.

Here is a program that demonstrates the bool type:

// Demonstrate bool values.

using System;

class BoolDemo {
 public static void Main() {
   bool b;

   b = false;
   Console.WriteLine("b is " + b);
   b = true;
   Console.WriteLine("b is " + b);

   // a bool value can control the if statement
   if(b) Console.WriteLine("This is executed.");

   b = false;
   if(b) Console.WriteLine("This is not executed.");

   // outcome of a relational operator is a bool value
   Console.WriteLine("10 > 9 is " + (10 > 9));
 }
}

The output generated by this program is shown here:

b is False
b is True
This is executed.
10 > 9 is True

There are three interesting things to notice about this program. First, as you can see, when a bool value is output by WriteLine( ), “True” or “False” is displayed. Second, the value of a bool variable is sufficient, by itself, to control the if statement. There is no need to write an if statement like this:

if(b == true) ...

Third, the outcome of a relational operator, such as <, is a bool value. This is why the expression 10 > 9 displays the value “True.” Further, the extra set of parentheses around 10 > 9 is necessary because the + operator has a higher precedence than the >.

No comments:

Post a Comment

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail