Home

Introduction to Conditions: Boolean Variables

 

Introduction

When interacting with a computer, a user submits values to a running application. Some of these values are valid. Some other values must be rejected or changed. To take care of these, the values must be checked, examined, re-examined, etc. The validity of a value is checked against its type. For example, a number can be checked as being equal to another. A condition can be checked as being true. A measure can be checked as to whether it is higher than a certain threshold.

To perform the necessary validations of values, the C# language provides some symbols, referred to as Boolean operators.

Practical LearningPractical Learning: Introducing Boolean Variables

  1. Start Microsoft Visual C#
  2. Create a new Console Application named FlowerShop1
  3. To create a new class, on the main menu, click Project -> Add Class...
  4. Set the Name of the class to Flower and click Add
  5. Complete the Flower.cs file as follows:
     
    using System;
    
    namespace FlowerShop1
    {
        class Flower
        {
            public int Type;
            public int Color;
            public char Arrangement;
            public decimal UnitPrice;
    
            public Flower()
            {
                Type = 0;
                Color = 0;
                Arrangement = 'B';
                UnitPrice = 0.00M;
            }
    
            public Flower(int type)
            {
                Type = type;
                Color = 0;
                Arrangement = 'B';
                UnitPrice = 0.00M;
            }
    
            public Flower(int type, int color,
                    char argn, decimal price)
            {
                Type = type;
                Color = color;
                Arrangement = argn;
                UnitPrice = price;
            }
        }
    }
  6. To create a new class, in the Solution Explorer, right-click the project name, position the mouse on Add and click Class...
  7. Set the Name of the class to OrderProcessing and click Add
  8. Complete the OrderProcessing.cs file as follows:
     
    using System;
    
    namespace FlowerShop1
    {
        class OrderProcessing
        {
            public OrderProcessing()
            {
                FlowerOrder = new Flower();
            }
    
            public Flower FlowerOrder;
            public int Quantity;
    
            public decimal GetTotalPrice()
            {
                return Quantity * FlowerOrder.UnitPrice;
            }
        }
    }
  9. Access the Program.cs file and complete it as follows:
     
    using System;
    
    namespace FlowerShop1
    {
        class Program
        {
            private static OrderProcessing CreateFlowerOrder()
            {
                OrderProcessing order = new OrderProcessing();
                int type, color, qty;
                char arrangement;
                decimal price;
    
                Console.WriteLine("=======================");
                Console.WriteLine("==-=-=Flower Shop=-=-==");
                Console.WriteLine("-----------------------");
    
                Console.WriteLine("Enter the Type of Flower Order");
                Console.WriteLine("1. Roses");
                Console.WriteLine("2. Lilies");
                Console.WriteLine("3. Daisies");
                Console.WriteLine("4. Carnations");
                Console.WriteLine("5. Live Plant");
                Console.WriteLine("6. Mixed");
                Console.Write("Your Choice: ");
                type = int.Parse(Console.ReadLine());
    
                Console.WriteLine("Enter the Color");
                Console.WriteLine("1. Red");
                Console.WriteLine("2. White");
                Console.WriteLine("3. Yellow");
                Console.WriteLine("4. Pink");
                Console.WriteLine("5. Orange");
                Console.WriteLine("6. Blue");
                Console.WriteLine("7. Lavender");
                Console.WriteLine("8. Mixed");
                Console.Write("Your Choice: ");
                color = int.Parse(Console.ReadLine());
    
                Console.WriteLine("Enter the Type of Arrangement");
                Console.WriteLine("U. Bouquet");
                Console.WriteLine("V. Vase");
                Console.WriteLine("B. Basket");
                Console.WriteLine("M. Mixed");
                Console.Write("Your Choice: ");
                arrangement = char.Parse(Console.ReadLine());
    
                Console.Write("Enter the Unit Price: ");
                price = decimal.Parse(Console.ReadLine());
    
                Console.Write("Enter Quantity:       ");
                qty = int.Parse(Console.ReadLine());
    
                Flower flr = new Flower(type, color, arrangement, price);
                order.FlowerOrder = flr;
                order.Quantity = qty;
    
                return order;
            }
    
            private static void ShowFlowerOrder(OrderProcessing order)
            {
                Console.WriteLine("=======================");
                Console.WriteLine("==-=-=Flower Shop=-=-==");
                Console.WriteLine("-----------------------");
                Console.WriteLine("Flower Type:  {0}", order.FlowerOrder.Type);
                Console.WriteLine("Flower Color: {0}", order.FlowerOrder.Color);
           Console.WriteLine("Arrangement:  {0}", order.FlowerOrder.Arrangement);
           Console.WriteLine("Price:        {0:C}", order.FlowerOrder.UnitPrice);
                Console.WriteLine("Quantity:     {0}", order.Quantity);
                Console.WriteLine("Total Price:  {0:C}", order.GetTotalPrice());
                Console.WriteLine("=======================");
            }
    
            static void Main()
            {
                OrderProcessing flower = CreateFlowerOrder();
                Console.WriteLine();
    
                ShowFlowerOrder(flower);
                Console.WriteLine();
            }
        }
    }
  10. Execute the application and test it. Here is an example:
     
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Enter the Type of Flower Order
    1. Roses
    2. Lilies
    3. Daisies
    4. Carnations
    5. Live Plant
    6. Mixed
    Your Choice: 4
    Enter the Color
    1. Red
    2. White
    3. Yellow
    4. Pink
    5. Orange
    6. Blue
    7. Lavender
    8. Mixed
    Your Choice: 6
    Enter the Type of Arrangement
    U. Bouquet
    V. Vase
    B. Basket
    M. Mixed
    Your Choice: V
    Enter the Unit Price: 37.95
    Enter Quantity:       2
    
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  4
    Flower Color: 6
    Arrangement:  V
    Price:        $37.95
    Quantity:     2
    Total Price:  $75.90
    =======================
    
    Press any key to continue . . .
  11. Close the DOS window

Declaring a Boolean Variable

A variable is referred to as Boolean if it can hold a value that is either true or false. To declare a Boolean variable, you can use the bool keyword. Here is an example:

using System;

class Program
{
    static void Main()
    {
        bool drinkingUnderAge;
    }
}

Alternatively, you can declare a Boolean variable using the Boolean data type. The Boolean data type is part of the System namespace. Here is an example:

using System;

class Program
{
    static void Main()
    {
        bool drinkingUnderAge;
    	Boolean TheFloorIsCoveredWithCarpet;
    }
}

After the variable has been declared, you must initialize with a true or a false value. Here is an example:

using System;

class Program
{
    static void Main()
    {
        bool drinkingUnderAge = true;
    }
}

To display the value of a Boolean variable on the console, you can type its name in the parentheses of the Write() or the WriteLine() methods of the Console class. Here is an example:

using System;

class Program
{
    static void Main()
    {
        bool drinkingUnderAge = true;
        
        Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
    }
}

This would produce:

Drinking Under Age: True
Press any key to continue . . .

At any time and when you judge it necessary, you can change the value of the Boolean variable by assigning it a true or false value. Here is an example:

using System;

class Program
{
    static void Main()
    {
        bool drinkingUnderAge = true;
        Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);

        drinkingUnderAge = false;
        Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
    }
}

This would produce:

Drinking Under Age: True
Drinking Under Age: False
Press any key to continue . . .

Retrieving the Value of a Boolean Variable

As reviewed for the other data types, you can request the value of a Boolean variable from the user. In this case, the user must type either True (or true) or False (or false) and you can retrieve it using the Read() or the ReadLine() methods of the Console class. Here is an example:

using System;

class Program
{
    static void Main()
    {
        bool drivingUnderAge = false;

        Console.WriteLine("Were you driving under age?");
        Console.Write("If Yes, enter True. Otherwise enter False: ");
        drivingUnderAge = bool.Parse(Console.ReadLine());

        Console.WriteLine("\nWas Driving Under Age: {0}\n", drivingUnderAge);
    }
}

Here is an example of running the program:

Were you driving under age?
If Yes, enter True. Otherwise enter False: true

Was Driving Under Age: True

Press any key to continue . . .

Creating a Boolean Field

Like the other types of variables we used in previous lessons, a Boolean variable can be made a field of a class. You declare it like any other variable, using the bool keyword or the Boolean data type. Here is an example:

public class House
{
    public char TypeOfHome;
    public int Bedrooms;
    public Single Bathrooms;
    public Byte Stories;
    public bool HasCarGarage;
    public int YearBuilt;
    public double Value;
}

When initializing an object that has a Boolean variable as a member, simply assign true or false to the variable. In the same way, you can retrieve or check the value that a Boolean member variable is holding by simply accessing it. Here are examples:

using System;

public class House
{
    public char TypeOfHome;
    public int Bedrooms;
    public Single Bathrooms;
    public Byte Stories;
    public bool HasCarGarage;
    public int YearBuilt;
    public double Value;
}

class Program
{
    static void Main()
    {
        House condominium = new House();

        condominium.HasCarGarage = false;
        condominium.YearBuilt = 2002;
        condominium.Bathrooms = 1.5F;
        condominium.Stories = 18;
        condominium.Value = 155825;
        condominium.Bedrooms = 2;
        condominium.TypeOfHome = 'C';

        Console.WriteLine("=//= Altair Realty =//=");
        Console.WriteLine("=== Property Listing ===");
        Console.WriteLine("Type of Home:        {0}", condominium.TypeOfHome);
        Console.WriteLine("Number of Bedrooms:  {0}", condominium.Bedrooms);
        Console.WriteLine("Number of Bathrooms: {0}", condominium.Bathrooms);
        Console.WriteLine("Number of Stories:   {0}", condominium.Stories);
        Console.WriteLine("Year Built:          {0}", condominium.YearBuilt);
        Console.WriteLine("Has Car Garage:      {0}", condominium.HasCarGarage);
        Console.WriteLine("Monetary Value:      {0}\n", condominium.Value);
    }
}

This would produce:

=//= Altair Realty =//=
=== Property Listing ===
Type of Home:        C
Number of Bedrooms:  2
Number of Bathrooms: 1.5
Number of Stories:   18
Year Built:          2002
Has Car Garage:      False
Monetary Value:      155825

Press any key to continue . . .

Boolean Arguments

Like parameters of the other types, you can pass an argument of type bool or Boolean to a method. Such an argument would be treated as holding a true or false value.

 

Copyright © 2006-2016, FunctionX, Inc. Next