![]() |
Introduction to Conditions |
|
Boolean Values |
|
Introduction |
The essence of computer programming relies on telling the computer what to do when something occurs, and how to do it. This is performed by setting conditions, examining them and stating what decisions the computer should make.
VBasic uses various conditional statements for almost any situation your computer can encounter. As the application developer, it is up to you to anticipate these situations and make your program act accordingly.
A Boolean variable is one whose value can be either True or False. To declare such a variable, use the Boolean keyword. Here is an example:
Sub Main()
Dim IsMarried As Boolean
End Sub
By default, a Boolean variable is initialized with False. If you want, you can otherwise initialize it with a True value. After declaring a Boolean variable, you can use it to test its value and to involve it in other conditional statements.
|
Introduction to Boolean Built-In Functions |
To convert a value to Boolean, you can use CBool().
|
Introduction |
An enumeration is a list of values with each represented by a name. Enumerations are highly useful in conditional statements because they allow using recognizable names to identify confusing values.
To create an enumeration, use the Enum keyword followed by a name. The creation of an enumeration must end with End Enum:
Enum MembershipType End Enum
Between the Enum Name and the End Enum lines, you can enter the values of the enumerations, also called members of the enumeration. Each member must be on its own line. Here is an example:
Enum MembershipType
Teen
Adult
Senior
End Enum
Each member of the enumeration holds a value of a natural number, such as 0, 4, 12, 25, etc. After creating an enumeration, you can declare a variable from it. For example, you can declare a variable of a MembershipType type as follows:
Imports System
Public Module Exercise
Enum MembershipType
Teen
Adult
Senior
End Enum
Sub Main()
Dim MType As MembershipType
End Sub
End Module
After declaring such a variable, to initialize it, specify which member of the enumeration would be given to it. You should only assign a known member of the enumeration. To do this, on the right side of the assignment operator, type the name of the enumeration, followed by the period operator, and followed by the member whose value you want to assign. Here is an example:
Imports System
Public Module Exercise
Enum MembershipType
Teen
Adult
Senior
End Enum
Sub Main()
Dim MType As MembershipType
MType = MembershipType.Senior
End Sub
End Module
You can also find out what value the declared variable is currently holding. For example, you can display it on the console using Write() or WriteLine(). Here is an example:
Imports System
Public Module Exercise
Enum MembershipType
Teen
Adult
Senior
End Enum
Sub Main()
Dim MType As MembershipType
MType = MembershipType.Senior
Console.WriteLine("Membership Type: " & MType)
End Sub
End Module
This would produce:
Membership Type: 2
As seen on this example, an enumeration is in fact a list of numbers where each member of the list is identified with a name. By default, the first item of the list has a value of 0, the second has a value of 1, etc. Based on this, on the MembershipType enumerator, Teen has a value of 0 while Senior has a value of 2. These are the default values. If you don't want these values, you can explicitly define the value of one or each member of the list. Suppose you want the Teen member in the above enumeration to have a value of 5. To do this, use the assignment operator "=" to give the desired value. The enumerator would be:
Enum MembershipType
Teen = 5
Adult
Senior
End Enum
In this case, Teen now would now have a value of 5, Adult would have a value of 6, and Senior would have a value of 7. You can also assign a value to more than one member of an enumeration. Here is an example:
Enum MembershipType
Teen = 3
Adult = 8
Senior
End Enum
In this case, Senior would have a value of 9.
An enumeration is very useful in a Select Case statement where it can be used in case sections. An advantage of using an enumerator is its ability to be more explicit than a regular integer. To use an enumeration, define it and list each one of its members for the case that applies. Here is an example of a Select Case statement that uses an enumeration.
Imports System
Public Module Exercise
Enum EmploymentStatus
FullTime
PartTime
Contractor
NotSpecified
End Enum
Sub Main()
Dim EmplStatus As Integer
Console.WriteLine("Employee's Contract Status: ")
Console.WriteLine("0 - Full Time | 1 - Part Time")
Console.WriteLine("2 - Contractor | 3 - Other")
Console.Write("Status: ")
Dim Status As String = Console.ReadLine()
EmplStatus = Integer.Parse(Status)
Console.WriteLine()
Select Case EmplStatus
Case EmploymentStatus.FullTime
Console.WriteLine("Employment Status: Full Time")
Console.WriteLine("Employee's Benefits: Medical Insurance")
Console.WriteLine(" Sick Leave")
Console.WriteLine(" Maternal Leave")
Console.WriteLine(" Vacation Time")
Console.WriteLine(" 401K")
Case EmploymentStatus.PartTime
Console.WriteLine("Employment Status: Part Time")
Console.WriteLine("Employee's Benefits: Sick Leave")
Console.WriteLine(" Maternal Leave")
Case EmploymentStatus.Contractor
Console.WriteLine("Employment Status: Contractor")
Console.WriteLine("Employee's Benefits: None")
Case EmploymentStatus.NotSpecified
Console.WriteLine("Employment Status: Other")
Console.WriteLine("Status Not Specified")
Case Else
Console.WriteLine("Unknown Status\n")
End Select
End Sub
End Module
Here is an example of running the program:
Employee's Contract Status: 0 - Full Time | 1 - Part Time 2 - Contractor | 3 - Other Status: 0 Employment Status: Full Time Employee's Benefits: Medical Insurance Sick Leave Maternal Leave Vacation Time 401K Press any key to continue
|
|
Imports System
Public Module Exercise
Enum TypeOfApplication
NewDriversLicense = 1
UpgradeFromIDCard
TransferFromAnotherState
End Enum
Sub Main()
Dim FirstName As String, LastName As String
Dim OrganDonorAnswer As String
Dim Sex As Char, Gender As String
Dim DLClass As String
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Application ---")
Console.WriteLine(" - Select the type of application -")
Console.WriteLine("1 - Applying for a brand new Driver's License")
Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License")
Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state")
Console.Write("Your Choice: ")
Dim itype As Integer = CInt(Console.ReadLine())
Console.Write("First Name: ")
FirstName = Console.ReadLine()
Console.Write("Last Name: ")
LastName = Console.ReadLine()
Console.Write("Sex(F=Female/M=Male): ")
Sex = char.Parse(Console.ReadLine())
Console.WriteLine(" - Driver's License Class -")
Console.WriteLine("A - All Non-commercial vehicles except motorcycles")
Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs.")
Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.")
Console.WriteLine("K - Mopeds")
Console.WriteLine("M - Motorcycles")
Console.Write("Your Choice: ")
DLClass = char.Parse(Console.ReadLine())
Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
OrganDonorAnswer = Console.ReadLine()
if Sex = "f" Then
Gender = "Female"
ElseIf Sex = "F" Then
Gender = "Female"
ElseIf Sex = "m" Then
Gender = "Male"
ElseIf Sex = "M" Then
Gender = "Male"
else
Gender = "Unknown"
End If
Console.WriteLine()
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Information ---")
Console.Write("Type of Application: ")
Select Case iType
case TypeOfApplication.NewDriversLicense
Console.WriteLine("New Driver's License")
case TypeOfApplication.UpgradeFromIDCard
Console.WriteLine("Upgrade From Identity Card")
case TypeOfApplication.TransferFromAnotherState
Console.WriteLine("Transfer From Another State")
Case Else
Console.WriteLine("Not Specified")
End Select
Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
Console.WriteLine("Sex: {0}", Gender)
Select Case DLClass
case "a", "A"
Console.WriteLine("Class: A")
case "b", "B"
Console.WriteLine("Class: B")
case "c", "C"
Console.WriteLine("Class: C")
case "k", "K"
Console.WriteLine("Class: K")
case "m", "M"
Console.WriteLine("Class: M")
Case Else
Console.WriteLine("Class: Unknown")
End Select
Console.Write("Organ Donor? ")
if OrganDonorAnswer = "1" Then
Console.WriteLine("Yes")
ElseIf OrganDonorAnswer = "0" Then
Console.WriteLine("No")
Else
Console.WriteLine("N/A")
End If
Console.WriteLine()
End Sub
End Module
|
|
The Access Modifier of an Enumeration |
|
Built-In Enumerations |
|
Introduction |
A program is a series of instructions that ask the computer (actually the compiler) to check some situations and to act accordingly. To check such situations, the computer spends a great deal of its time performing comparisons between values. A comparison is a Boolean operation that produces a true or a false result, depending on the values on which the comparison is performed.
A comparison is performed between two values of the same type; for example, you can compare two numbers, two characters, or the names of two cities. On the other hand, a comparison between two disparate values doesn't bear any meaning. For example, it is difficult to compare a telephone number and somebody's age, or a music category and the distance between two points. Like the binary arithmetic operations, the comparison operations are performed on two values. Unlike arithmetic operations where results are varied, a comparison produces only one of two results. The result can be a logical true or a logical false. When a comparison is true, it has an integral value of 1 or positive; that is, a value greater than 0. If the comparison is not true, it is considered false and carries an integral value of 0.
The C# language is equipped with various operators used to perform any type of comparison between similar values. The values could be numeric, strings, or objects (operations on objects are customized in a process referred to as Operator Overloading).
There are primary assumptions you should make when writing statements used in conditions:
In your programs, make sure you clearly formulate your statements. This would make your programs easy to read and troubleshoot when problems occur (not if, but when).
To compare two variables for equality, use the = operator. Its syntax is:
Value1 = Value2
The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the value of Value1 would be compared with the value of Value2. If Value1 and Value2 hold the same value, the comparison produces a True result. If they are different, the comparison renders false or 0.
|
|
![]() |
|
![]() |
|
Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim IsFullTime As Boolean
Console.WriteLine("Is Employee Full Time? {0}", IsFullTime)
IsFullTime = True
Console.WriteLine("Is Employee Full Time? {0}", IsFullTime)
End Sub
End Module
This would produce: Is Employee Full Time? False Is Employee Full Time? True
|
|
As opposed to checking for equality, you may instead want to know whether two values are different. The operator used to perform this comparison is <> and its formula is: Variable1 <> Variable2
|
![]() |
|
If the operands on both sides of the operator are the same, the comparison renders false. If both operands hold different values, then the comparison produces a true result. This also shows that the equality = and the inequality <> operators are opposite. |
|
To find out whether one value is lower than another, use the < operator. Its syntax is: Value1 < Value2 The value held by Value1 is compared to that of Value2. As it would be done with other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a True.
|
![]() |
|
Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim PartTimeSalary, ContractorSalary As Double
Dim IsLower As Boolean
PartTimeSalary = 20.15
ContractorSalary = 22.48
IsLower = PartTimeSalary < ContractorSalary
Console.WriteLine("Part Time Salary: {0}", PartTimeSalary)
Console.WriteLine("Contractor Salary: {0}", ContractorSalary)
Console.WriteLine("Is PartTimeSalary < ContractorSalary? {0}", IsLower)
PartTimeSalary = 25.55
ContractorSalary = 12.68
IsLower = PartTimeSalary < ContractorSalary
Console.WriteLine()
Console.WriteLine("Part Time Salary: {0}", PartTimeSalary)
Console.WriteLine("Contractor Salary: {0}", ContractorSalary)
Console.WriteLine("Is PartTimeSalary < ContractorSalary? {0}", IsLower)
Console.WriteLine()
End Sub
End Module
This would produce: Part Time Salary: 20.15 Contractor Salary: 22.48 Is PartTimeSalary < ContractorSalary? True Part Time Salary: 25.55 Contractor Salary: 12.68 Is PartTimeSalary < ContractorSalary? False
|
|
The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is: Value1 <= Value2 The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 hold the same value, result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true: |
![]() |
|
When two values of the same type are distinct, one of them is usually higher than the other. VBasic provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its syntax is: Value1 > Value2 Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a True value. Otherwise, the comparison renders False or null.
|
![]() |
|
Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim PartTimeSalary, ContractorSalary As Double
Dim IsLower As Boolean
PartTimeSalary = 20.15
ContractorSalary = 22.48
IsLower = PartTimeSalary > ContractorSalary
Console.WriteLine("Part Time Salary: {0}", PartTimeSalary)
Console.WriteLine("Contractor Salary: {0}", ContractorSalary)
Console.WriteLine("Is PartTimeSalary > ContractorSalary? {0}", IsLower)
PartTimeSalary = 25.55
ContractorSalary = 12.68
IsLower = PartTimeSalary > ContractorSalary
Console.WriteLine()
Console.WriteLine("Part Time Salary: {0}", PartTimeSalary)
Console.WriteLine("Contractor Salary: {0}", ContractorSalary)
Console.WriteLine("Is PartTimeSalary > ContractorSalary? {0}", IsLower)
Console.WriteLine()
End Sub
End Module
This would produce: Part Time Salary: 20.15 Contractor Salary: 22.48 Is PartTimeSalary > ContractorSalary? False Part Time Salary: 25.55 Contractor Salary: 12.68 Is PartTimeSalary > ContractorSalary? True
|
|
The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is: Value1 >= Value2 A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a True value. If the value of the left operand is greater than that of the right operand, the comparison still produces True. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a False result.
|
![]() |
|
Enumerations |
|
Introduction |
Consider that, when creating a program for a real estate company that sells houses, you want the program to ask a customer the type of house that he or she wants to purchase and/or the type of garage that the desired house should have. Here is an example:
using System;
public class Exercise
{
static int Main()
{
int TypeOfHouse = 0;
int TypeOfGarage = 0;
Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Townhouse");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice: ");
TypeOfHouse = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the type of garage you want");
Console.WriteLine("0 - Doesn't matter");
Console.WriteLine("1 - Interior");
Console.WriteLine("2 - Exterior");
Console.Write("Your Choice: ");
TypeOfGarage = int.Parse(Console.ReadLine());
Console.WriteLine("\nHouse Type: {0}", TypeOfHouse);
Console.WriteLine("Garage Type: {0}", TypeOfGarage);
return 0;
}
}
Here is an example of running the program:
Enter the type of house you want to purchase 1 - Single Family 2 - Townhouse 3 - Condominium Your Choice: 3 Enter the type of garage you want 0 - Doesn't matter 1 - Interior 2 - Exterior Your Choice: 1 House Type: 3 Garage Type: 1 Press any key to continue . . .
For such a program, the numbers can be vague. 1 can be considered a general number but, in our program, it can represent a Single Family house or an Interior type of garage. At the same time, our program uses the constant 1 in particular meaningful ways. To make it possible to give more meaning to a constant number, when the number can be made part of a series, C# allows you to create a type of list.
An enumeration is a series of constant integers that each has a specific position in the list and can be recognized by a meaningful name. Based on this, instead of just remembering that the constant 1 represents Single Family, you can create a list that has that type of house. In another list, instead of using 1 again, you can give it a name. Consequently, in each list, although the constant 1 would still be considered, at least it would mean something precise.
To create an enumeration, you use the enum keyword, followed by the name of the enumeration, followed by a name for each item of the list. The name of the enumerator and the name of each item of the list follows the rules we reviewed for names. The formula of creating an enumeration is:
enum Series_Name {Item1, Item2, Item_n};
Here is an example:
using System;
public class Exercise
{
enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
static int Main()
{
return 0;
}
}
|
Declaring an Enumeration Variable |
After creating an enumeration, each member of the enumeration holds a value of a natural number, such as 0, 4, 12, 25, etc. In C#, an enumeration cannot hold character values (of type char). After creating an enumeration, you can declare a variable from it. Here is an example:
using System;
public class Exercise
{
enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
static int Main()
{
HouseType propType;
return 0;
}
}
Just as done with the other types, you can use the var keyword to declare a variable of an enumeration type.
|
Initializing an Enumeration Variable |
After declaring a variable for an enumeration, to initialize it, specify which member of the enumeration would be assigned to the variable. You should only assign a known member of the enumeration. To do this, on the right side of the assignment operator, type the name of the enumeration, followed by the period operator, and followed by the member whose value you want to assign. Here is an example:
using System;
public class Exercise
{
enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
static int Main()
{
var propType = HouseType.SingleFamily;
return 0;
}
}
You can also find out what value the declared variable is currently holding. For example, you can display it on the console using Write() or WriteLine(). Here is an example:
using System;
public class Exercise
{
enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
static int Main()
{
var propType = HouseType.SingleFamily;
Console.WriteLine("House Type: {0}", propType);
return 0;
}
}
This would produce:
House Type: SingleFamily Press any key to continue . . .
An enumeration is in fact a list of numbers where each member of the list is identified with a name. By default, the first item of the list has a value of 0, the second has a value of 1, and so on. For example, on the HouseType enumeration, Unknown has a value of 0 while Townhouse has a value of 2. These are the default values. If you don't want these values, you can specify the value of one or each member of the list. Suppose you want the Unknown member in the above enumeration to have a value of 5. To do this, use the assignment operator "=" to give the desired value. The enumerator would be:
using System;
public class Exercise
{
enum HouseType { Unknown = 5, SingleFamily, TownHouse, Condominium }
static int Main()
{
return 0;
}
}
In this case, Unknown now would have a value of 5, SingleFamily would have a value of 6 because it follows a member whose value is 1 (thus 5 + 1 = 6). Townhouse would have a value of 7, and Condominium would have a value of 8. You can also assign a value to more than one member of an enumeration. Here is an example:
using System;
public class Exercise
{
enum HouseType { Unknown = 3, SingleFamily = 12, TownHouse, Condominium = 8 }
static int Main()
{
return 0;
}
}
In this case, Townhouse would have a value of 13 because it follows SingleFamily that has a value of 12.
|
Enumerations Visibility |
By default, if you create an enumeration the way we have proceeded so far, it would be available only in the project it belongs to. As done for a class, you can control an enumeration's accessibility outside of its project. This means that you can hide or make it visible outside of its project. To do this, you can precede it with the private or the public keyword. Here is an example:
using System;
public class Exercise
{
public enum HouseType
{
Unknown,
SingleFamily,
TownHouse,
Condominium
}
static int Main()
{
HouseType propType = HouseType.SingleFamily;
Console.WriteLine("House Type: {0}", propType);
return 0;
}
}
|
An Enumeration as a Member Variable |
After creating an enumeration, you can use it as a data type to declare a variable. To create a field that is of an enumeration type, follow the same rules as done for the primitive types: the name of the enumeration, followed by the name of the variable, and followed by a semi-colon. Here is an example:
public enum HouseType
{
Unknown,
SingleFamily,
TownHouse,
Condominium
}
public class House
{
HouseType PropertyType;
}
In the same way, you can declare as many enumeration variables as you want. After declaring the variable, to initialize it, assign it the desired member of the enumeration. Here is an example:
public enum HouseType
{
Unknown,
SingleFamily,
TownHouse,
Condominium
}
public class House
{
HouseType PropertyType;
public House()
{
PropertyType = HouseType.Unknown;
}
}
Once the member variable has been initialized, you can use it as you see fit as we will learn and practice in future sections and lessons. At a minimum, you can pass it to Write() or WriteLine() to display its value. Here is an example:
using System;
public enum HouseType
{
Unknown,
SingleFamily,
TownHouse,
Condominium
}
public class House
{
public HouseType PropertyType;
public House()
{
PropertyType = HouseType.Unknown;
}
public void Display()
{
Console.WriteLine("Property Type: {0}", PropertyType);
}
}
public class Exercise
{
static int Main()
{
var propType = new House();
propType.Display();
Console.WriteLine();
propType.PropertyType = HouseType.SingleFamily;
propType.Display();
Console.WriteLine();
return 0;
}
}
This would produce:
Property Type: Unknown Property Type: SingleFamily Press any key to continue . . .
Using it as normal data type, you can create a method that returns an enumeration. You can also pass an enumeration to a method as argument.
|
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlowerShop1
{
public enum FlowerType
{
Roses = 1,
Lilies,
Daisies,
Carnations,
LivePlant,
Mixed
}
public enum FlowerColor
{
Red = 1,
White,
Yellow,
Pink,
Orange,
Blue,
Lavender,
Mixed
}
public enum FlowerArrangement
{
Bouquet = 1,
Vase,
Basket,
Mixed
}
public class Flower
{
public FlowerType Type;
public FlowerColor Color;
public FlowerArrangement Arrangement;
public decimal UnitPrice;
public Flower()
{
Type = FlowerType.Mixed;
Color = FlowerColor.Mixed;
Arrangement = FlowerArrangement.Vase;
UnitPrice = 0.00M;
}
public Flower(FlowerType type)
{
Type = type;
Color = FlowerColor.Mixed;
Arrangement = FlowerArrangement.Vase;
UnitPrice = 0.00M;
}
public Flower(FlowerType type, FlowerColor color,
FlowerArrangement argn, decimal price)
{
Type = type;
Color = color;
Arrangement = argn;
UnitPrice = price;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlowerShop1
{
public class Program
{
private static OrderProcessing CreateFlowerOrder()
{
OrderProcessing order = new OrderProcessing();
int type, color, qty;
int 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("1. Bouquet");
Console.WriteLine("2. Vase");
Console.WriteLine("3. Basket");
Console.WriteLine("4. Mixed");
Console.Write("Your Choice: ");
arrangement = int.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((FlowerType)type,
(FlowerColor)color,
(FlowerArrangement)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(string[] args)
{
OrderProcessing flower = CreateFlowerOrder();
Console.WriteLine();
ShowFlowerOrder(flower);
Console.WriteLine();
}
}
}
|
======================= ==-=-=Flower Shop=-=-== ----------------------- Enter the Type of Flower Order 1. Roses 2. Lilies 3. Daisies 4. Carnations 5. Live Plant 6. Mixed Your Choice: 5 Enter the Color 1. Red 2. White 3. Yellow 4. Pink 5. Orange 6. Blue 7. Lavender 8. Mixed Your Choice: 7 Enter the Type of Arrangement 1. Bouquet 2. Vase 3. Basket 4. Mixed Your Choice: 3 Enter the Unit Price: 35.95 Enter Quantity: 4 ======================= ==-=-=Flower Shop=-=-== ----------------------- Flower Type: LivePlant Flower Color: Lavender Arrangement: Basket Price: $35.95 Quantity: 4 Total Price: $143.80 ======================= Press any key to continue . . . |
|
Condition Checking |
|
Introduction |
|
In some programming assignments, you must find out whether a given situation bears a valid value. This is done by checking a condition. To support this, VBasic provides a series of words that can be combined to perform this checking. Checking a condition usually produces a True or a False result. Once the condition has been checked, you can use the result (as True or False) to take action. Because there are different ways to check a condition, there are also different types of keywords to check different things. To use them, you must be aware of what each does or cannot do so you would select the right one. |
|
|
Imports System
Public Module Exercise
Sub Main()
Dim FirstName As String, LastName As String
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Application ---")
Console.Write("First Name: ")
FirstName = Console.ReadLine()
Console.Write("Last Name: ")
LastName = Console.ReadLine()
Console.WriteLine()
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Information ---")
Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
Console.WriteLine()
End Sub
End Module
|

|
Introduction |
The If...Then statement examines the truthfulness of an expression. Structurally, its formula is:
If ConditionToCheck Then Statement
Therefore, the program examines a condition, in this case ConditionToCheck. This ConditionToCheck can be a simple expression or a combination of expressions. If the ConditionToCheck is true, then the program will execute the Statement.
There are two ways you can use the If...Then statement. If the conditional formula is short enough, you can write it on one line, like this:
If ConditionToCheck Then Statement
Here is an example:
Imports System
Public Module Exercise
Sub Main()
Dim IsMarried As Boolean
Dim TaxRate As Double
Console.WriteLine("Tax Rate: {0:F}", TaxRate)
IsMarried = True
If IsMarried Then TaxRate = 30.65
Console.WriteLine("Tax Rate: {0:F}", TaxRate)
End Sub
End Module
This would produce:
Tax Rate: 0.00 Tax Rate: 30.65 Press any key to continue
If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if the condition you are examining is short. In this case, one very important rule to keep is to terminate the conditional statement with End If. The formula used is:
If ConditionToCheck Then Statement End If
Here is an example:
Imports System
Public Module Exercise
Sub Main()
Dim IsMarried As Boolean
Dim TaxRate As Double
Console.WriteLine("Tax Rate: {0:F}", TaxRate)
IsMarried = True
If IsMarried Then
TaxRate = 30.65
Console.WriteLine("Tax Rate: {0:F}", TaxRate)
End If
End Sub
End Module
|
|
Imports System
Public Module Exercise
Sub Main()
Dim FirstName As String, LastName As String
Dim OrganDonorAnswer As String
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Application ---")
Console.Write("First Name: ")
FirstName = Console.ReadLine()
Console.Write("Last Name: ")
LastName = Console.ReadLine()
Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
OrganDonorAnswer = Console.ReadLine()
Console.WriteLine()
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Information ---")
Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
Console.Write("Organ Donor? ")
if OrganDonorAnswer = "1" Then Console.WriteLine("Yes")
Console.WriteLine()
End Sub
End Module
|
C:\VBasic\MVA1>vbc Exercise.vb Microsoft (R) Visual Basic .NET Compiler version 7.10.3052.4 for Microsoft (R) .NET Framework version 1.1.4322.573 Copyright (C) Microsoft Corporation 1987-2002. All rights reserved. C:\VBasic\MVA1>Exercise -=- Motor Vehicle Administration -=- --- Driver's License Application --- First Name: Ernestine Last Name: Ardant Are you willing to be an Organ Donor(1=Yes/0=No)? 1 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Full Name: Ernestine Ardant Organ Donor? Yes |
|
Built-In If...Then Functions |
|
Logical Functions |
|
Is it Empty? |
A logical function is one that checks whether an expression is true or false and then return a Boolean value.
The IsEmpty function check whether a field is empty. Its syntax is:
IsEmpty(Expression)
In this case, the Expression argument will be checked. If it is empty, the IsEmpty function returns True. If the expression or field is not empty, that is, if it contains something, the function returns False.
|
Is it Null? |
Another problem you may encounter when involving an operation or the contents of a control is whether it has never contained a value. This operation is sometimes confused with that of checking whether a field is empty. Here is the difference (it is important to understand this because it is used in many other environments):
To check whether an expression or the value of a control is null, you can call the IsNull() function. Its syntax is:
IsNull(Expression)
Also used on fields, the IsNull() function checks the state of a field (remember, this functions does not check whether a field is empty or not; it checks if the field has ever contained a value). If the field it null, this function returns True. If the field is not null, this function returns False.
|
Introduction |
|
The If...Then statement offers only one alternative: to act if the condition is true. Whenever you would like to apply an alternate expression in case the condition is false, you can use the If...Then...Else statement. The formula of this statement is: If ConditionToCheck Then Statement1 Else Statement2 End If When this section of code is executed, if the ConditionToCheck is true, then the first statement, Statement1, is executed. If the ConditionToCheck is false, the second statement, in this case Statement2, is executed. Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim MemberAge As Int16
Dim MemberCategory As String
MemberAge = 16
If MemberAge <= 18 Then
MemberCategory = "Teen"
Else
MemberCategory = "Adult"
End If
Console.WriteLine("Membership: {0}", MemberCategory)
End Sub
End Module
This would produce: Membership: Teen
|
|
|
Imports System
Public Module Exercise
Sub Main()
Dim FirstName As String, LastName As String
Dim OrganDonorAnswer As String
Dim Sex As Char
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Application ---")
Console.Write("First Name: ")
FirstName = Console.ReadLine()
Console.Write("Last Name: ")
LastName = Console.ReadLine()
Console.Write("Sex(F=Female/M=Male): ")
Sex = char.Parse(Console.ReadLine())
Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
OrganDonorAnswer = Console.ReadLine()
Console.WriteLine()
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Information ---")
Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
Console.WriteLine("Sex: {0}", Sex)
Console.Write("Organ Donor? ")
if OrganDonorAnswer = "1" Then
Console.WriteLine("Yes")
Else
Console.WriteLine("No")
End If
Console.WriteLine()
End Sub
End Module
|
|
The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offers as many choices as necessary. The formula is: If Condition1 Then Statement1 ElseIf Condition2 Then Statement2 ElseIf Conditionk Then Statementk End If The program will first examine Condition1. If Condition1 is true, the program will execute Statment1 and stop examining conditions. If Condition1 is false, the program will examine Condition2 and act accordingly. Whenever a condition is false, the program will continue examining the conditions until it finds one. Once a true condition has been found and its statement executed, the program will terminate the conditional examination at End If. Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim MemberAge As Int16
Dim MemberCategory As String
MemberAge = 32
If MemberAge <= 18 Then
MemberCategory = "Teen"
ElseIf MemberAge < 55 Then
MemberCategory = "Adult"
End If
Console.WriteLine("Membership: {0}", MemberCategory)
End Sub
End Module
This would produce; Membership: Adult There is still a possibility that none of the stated conditions is true. In this case, you should provide a "catch all" condition. This is done with a last Else section. The Else section must be the last in the list of conditions and would act if none of the primary conditions is true. The formula to use would be: If Condition1 Then
Statement1
ElseIf Condition2 Then
Statement2
ElseIf Conditionk Then
Statementk
Else
CatchAllStatement
End If
Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim MemberAge As Int16
Dim MemberCategory As String
MemberAge = 62
If MemberAge <= 18 Then
MemberCategory = "Teen"
ElseIf MemberAge < 55 Then
MemberCategory = "Adult"
Else
MemberCategory = "Senior"
End If
Console.WriteLine("Membership: {0}", MemberCategory)
End Sub
End Module
This would produce: Membership: Senior
|
|
|
Imports System
Public Module Exercise
Sub Main()
Dim FirstName As String, LastName As String
Dim OrganDonorAnswer As String
Dim Sex As Char, Gender As String
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Application ---")
Console.Write("First Name: ")
FirstName = Console.ReadLine()
Console.Write("Last Name: ")
LastName = Console.ReadLine()
Console.Write("Sex(F=Female/M=Male): ")
Sex = char.Parse(Console.ReadLine())
Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
OrganDonorAnswer = Console.ReadLine()
if Sex = "f" Then
Gender = "Female"
ElseIf Sex = "F" Then
Gender = "Female"
ElseIf Sex = "m" Then
Gender = "Male"
ElseIf Sex = "M" Then
Gender = "Male"
else
Gender = "Unknown"
End If
Console.WriteLine()
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Information ---")
Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
Console.WriteLine("Sex: {0}", Gender)
Console.Write("Organ Donor? ")
if OrganDonorAnswer = "1" Then
Console.WriteLine("Yes")
Else
Console.WriteLine("No")
End If
Console.WriteLine()
End Sub
End Module
|
C:\VBasic\MVA1>vbc Exercise.vb Microsoft (R) Visual Basic .NET Compiler version 7.10.3052.4 for Microsoft (R) .NET Framework version 1.1.4322.573 Copyright (C) Microsoft Corporation 1987-2002. All rights reserved. C:\VBasic\MVA1>Exercise -=- Motor Vehicle Administration -=- --- Driver's License Application --- First Name: Ernestine Last Name: Zola Sex(F=Female/M=Male): f Are you willing to be an Organ Donor(1=Yes/0=No)? 0 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Full Name: Ernestine Zola Sex: Female Organ Donor? No |
|
If...Then...Else-Based Function |
|
Introduction |
|
If you have a large number of conditions to examine, the If...Then...Else will go through each one of them. VBasic offers the alternative of jumping to the statement that applies to the state of the condition. The formula of the Select Case is: Select Case Expression Case Expression1 Statement1 Case Expression2 Statement2 Case Expressionk Statementk End Select The Expression will examined and evaluated once. Then it will compare the result of this examination with the Expression of each case. Once it finds one that matches, it would execute the corresponding Statement. Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim Answer As Byte
Console.WriteLine("One of the following is not a VBasic keyword")
Console.WriteLine("1) Function")
Console.WriteLine("2) Except")
Console.WriteLine("3) ByRef")
Console.WriteLine("4) Each")
Console.Write("Your Answer? ")
Answer = Console.ReadLine()
Select Case Answer
Case 1
Console.WriteLine("Wrong: Function is a VBasic keyword.")
Console.WriteLine("It is used to create a procedure of a function type")
Case 2
Console.WriteLine("Correct: Except is not a keyword in VBasic ")
Console.WriteLine("but __except is a C++ keyword used in Exception Handling")
Case 3
Console.WriteLine("Wrong: ByRef is a VBasic keyword used to pass an ")
Console.WriteLine("argument by reference to a procedure")
Case 4
Console.WriteLine("Wrong: The ""Each"" keyword is used in VBasic in a type ")
Console.WriteLine("of looping used to ""scan"" a list of item.")
End Select
Console.WriteLine()
End Sub
End Module
Here is an example of running the program: One of the following is not a VBasic keyword 1) Function 2) Except 3) ByRef 4) Each Your Answer? 2 Correct: Except is not a keyword in VBasic but __except is a C++ keyword used in Exception Handling If you anticipate that there could be no match between the Expression and one of the Expressions, you can use a Case Else statement at the end of the list. The statement would then look like this: Select Case Expression Case Expression1 Statement1 Case Expression2 Statement2 Case Expressionk Statementk Case Else Statementk End Select Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim Answer As Byte
Console.WriteLine("One of the following is not a VBasic keyword")
Console.WriteLine("1) Function")
Console.WriteLine("2) Except")
Console.WriteLine("3) ByRef")
Console.WriteLine("4) Each")
Console.Write("Your Answer? ")
Answer = Console.ReadLine()
Select Case Answer
Case 1
Console.WriteLine("Wrong: Function is a VBasic keyword.")
Console.WriteLine("It is used to create a procedure of a function type")
Case 2
Console.WriteLine("Correct: Except is not a keyword in VBasic ")
Console.WriteLine("but __except is a C++ keyword used in Exception Handling")
Case 3
Console.WriteLine("Wrong: ByRef is a VBasic keyword used to pass an ")
Console.WriteLine("argument by reference to a procedure")
Case 4
Console.WriteLine("Wrong: The ""Each"" keyword is used in VBasic in a type ")
Console.WriteLine("of looping used to ""scan"" a list of item.")
Case Else
Console.WriteLine("Invalid Selection")
End Select
Console.WriteLine()
End Sub
End Module
Here is an example of running the program: One of the following is not a VBasic keyword 1) Function 2) Except 3) ByRef 4) Each Your Answer? 8 Invalid Selection Instead of using one value for a case, you can apply more than one. To do this, on the right side of the Case keyword, separate the expressions with commas. You can also use a range of value for a case. To do this, on the right side of Case, enter the lower value, followed by To, followed by the higher value. Here is an example: Imports System
Public Module Exercise
Sub Main()
Dim age As Integer
age = 24
Select Case age
Case 0 To 17
Console.WriteLine("Teen")
Case 18 To 55
Console.WriteLine("Adult")
Case Else
Console.WriteLine("Senior")
End Select
End Sub
End Module
|
|
|
Imports System
Public Module Exercise
Sub Main()
Dim FirstName As String, LastName As String
Dim OrganDonorAnswer As String
Dim Sex As Char, Gender As String
Dim DLClass As String
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Application ---")
Console.Write("First Name: ")
FirstName = Console.ReadLine()
Console.Write("Last Name: ")
LastName = Console.ReadLine()
Console.Write("Sex(F=Female/M=Male): ")
Sex = char.Parse(Console.ReadLine())
Console.WriteLine(" - Driver's License Class -")
Console.WriteLine("A - All Non-commercial vehicles except motorcycles")
Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs.")
Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.")
Console.WriteLine("K - Mopeds")
Console.WriteLine("M - Motorcycles")
Console.Write("Your Choice: ")
DLClass = char.Parse(Console.ReadLine())
Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
OrganDonorAnswer = Console.ReadLine()
if Sex = "f" Then
Gender = "Female"
ElseIf Sex = "F" Then
Gender = "Female"
ElseIf Sex = "m" Then
Gender = "Male"
ElseIf Sex = "M" Then
Gender = "Male"
else
Gender = "Unknown"
End If
Console.WriteLine()
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Information ---")
Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
Console.WriteLine("Sex: {0}", Gender)
Select Case DLClass
case "a", "A"
Console.WriteLine("Class: A")
case "b", "B"
Console.WriteLine("Class: B")
case "c", "C"
Console.WriteLine("Class: C")
case "k", "K"
Console.WriteLine("Class: K")
case "m", "M"
Console.WriteLine("Class: M")
Case Else
Console.WriteLine("Class: Unknown")
End Select
Console.Write("Organ Donor? ")
if OrganDonorAnswer = "1" Then
Console.WriteLine("Yes")
ElseIf OrganDonorAnswer = "0" Then
Console.WriteLine("No")
Else
Console.WriteLine("N/A")
End If
Console.WriteLine()
End Sub
End Module
|
C:\VBasic\MVA1>vbc Exercise.vb Microsoft (R) Visual Basic .NET Compiler version 7.10.3052.4 for Microsoft (R) .NET Framework version 1.1.4322.573 Copyright (C) Microsoft Corporation 1987-2002. All rights reserved. C:\VBasic\MVA1>Exercise -=- Motor Vehicle Administration -=- --- Driver's License Application --- First Name: Paul Last Name: Dock Sex(F=Female/M=Male): M - Driver's License Class - A - All Non-commercial vehicles except motorcycles B - Non-commercial vehicles up to and including 26,001/more lbs. C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs. K - Mopeds M - Motorcycles Your Choice: c Are you willing to be an Organ Donor(1=Yes/0=No)? 1 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Full Name: Paul Dock Sex: Male Class: C Organ Donor? Yes C:\VBasic\MVA1> |
Imports System
Public Module Exercise
Enum EmploymentStatus
FullTime
PartTime
Contractor
NotSpecified
End Enum
Sub Main()
Dim EmplStatus As Integer
Console.WriteLine("Employee's Contract Status: ")
Console.WriteLine("0 - Full Time | 1 - Part Time")
Console.WriteLine("2 - Contractor | 3 - Other")
Console.Write("Status: ")
Dim Status As String = Console.ReadLine()
EmplStatus = Integer.Parse(Status)
Console.WriteLine()
Select Case EmplStatus
Case EmploymentStatus.FullTime
Console.WriteLine("Employment Status: Full Time")
Console.WriteLine("Employee's Benefits: Medical Insurance")
Console.WriteLine(" Sick Leave")
Console.WriteLine(" Maternal Leave")
Console.WriteLine(" Vacation Time")
Console.WriteLine(" 401K")
Case EmploymentStatus.PartTime
Console.WriteLine("Employment Status: Part Time")
Console.WriteLine("Employee's Benefits: Sick Leave")
Console.WriteLine(" Maternal Leave")
Case EmploymentStatus.Contractor
Console.WriteLine("Employment Status: Contractor")
Console.WriteLine("Employee's Benefits: None")
Case EmploymentStatus.NotSpecified
Console.WriteLine("Employment Status: Other")
Console.WriteLine("Status Not Specified")
Case Else
Console.WriteLine("Unknown Status\n")
End Select
End Sub
End Module
Here is an example of running the program:
Employee's Contract Status: 0 - Full Time | 1 - Part Time 2 - Contractor | 3 - Other Status: 0 Employment Status: Full Time Employee's Benefits: Medical Insurance Sick Leave Maternal Leave Vacation Time 401K Press any key to continue
|
|
Imports System
Public Module Exercise
Enum TypeOfApplication
NewDriversLicense = 1
UpgradeFromIDCard
TransferFromAnotherState
End Enum
Sub Main()
Dim FirstName As String, LastName As String
Dim OrganDonorAnswer As String
Dim Sex As Char, Gender As String
Dim DLClass As String
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Application ---")
Console.WriteLine(" - Select the type of application -")
Console.WriteLine("1 - Applying for a brand new Driver's License")
Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License")
Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state")
Console.Write("Your Choice: ")
Dim itype As Integer = CInt(Console.ReadLine())
Console.Write("First Name: ")
FirstName = Console.ReadLine()
Console.Write("Last Name: ")
LastName = Console.ReadLine()
Console.Write("Sex(F=Female/M=Male): ")
Sex = char.Parse(Console.ReadLine())
Console.WriteLine(" - Driver's License Class -")
Console.WriteLine("A - All Non-commercial vehicles except motorcycles")
Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs.")
Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.")
Console.WriteLine("K - Mopeds")
Console.WriteLine("M - Motorcycles")
Console.Write("Your Choice: ")
DLClass = char.Parse(Console.ReadLine())
Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
OrganDonorAnswer = Console.ReadLine()
if Sex = "f" Then
Gender = "Female"
ElseIf Sex = "F" Then
Gender = "Female"
ElseIf Sex = "m" Then
Gender = "Male"
ElseIf Sex = "M" Then
Gender = "Male"
else
Gender = "Unknown"
End If
Console.WriteLine()
Console.WriteLine(" -=- Motor Vehicle Administration -=-")
Console.WriteLine(" --- Driver's License Information ---")
Console.Write("Type of Application: ")
Select Case iType
case TypeOfApplication.NewDriversLicense
Console.WriteLine("New Driver's License")
case TypeOfApplication.UpgradeFromIDCard
Console.WriteLine("Upgrade From Identity Card")
case TypeOfApplication.TransferFromAnotherState
Console.WriteLine("Transfer From Another State")
Case Else
Console.WriteLine("Not Specified")
End Select
Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
Console.WriteLine("Sex: {0}", Gender)
Select Case DLClass
case "a", "A"
Console.WriteLine("Class: A")
case "b", "B"
Console.WriteLine("Class: B")
case "c", "C"
Console.WriteLine("Class: C")
case "k", "K"
Console.WriteLine("Class: K")
case "m", "M"
Console.WriteLine("Class: M")
Case Else
Console.WriteLine("Class: Unknown")
End Select
Console.Write("Organ Donor? ")
if OrganDonorAnswer = "1" Then
Console.WriteLine("Yes")
ElseIf OrganDonorAnswer = "0" Then
Console.WriteLine("No")
Else
Console.WriteLine("N/A")
End If
Console.WriteLine()
End Sub
End Module
|
|
Selection-Based Functions |
|
|
||
| Previous | Copyright © 2004-2005 Yevol | Next |
|
|
||
![]() |
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlowerShop1
{
public 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;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlowerShop1
{
public class OrderProcessing
{
public OrderProcessing()
{
FlowerOrder = new Flower();
}
public Flower FlowerOrder;
public int Quantity;
public decimal GetTotalPrice()
{
return Quantity * FlowerOrder.UnitPrice;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlowerShop1
{
public 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(string[] args)
{
OrderProcessing flower = CreateFlowerOrder();
Console.WriteLine();
ShowFlowerOrder(flower);
Console.WriteLine();
}
}
}
|
======================= ==-=-=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 . . . |
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 either the var or the bool keyword. Here is an example:
using System;
public class Exercise
{
static int Main()
{
bool DrinkingUnderAge;
return 0;
}
}
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;
public class Exercise
{
static int Main()
{
bool DrinkingUnderAge;
Boolean TheFloorIsCoveredWithCarpet;
return 0
}
}
After the variable has been declared, you must initialize it with a true or a false value. In fact, if you declare it as var, you must initialize it. Here is an example:
using System;
public class Exercise
{
static int Main()
{
var DrinkingUnderAge = true;
return 0;
}
}
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;
public class Exercise
{
static int Main()
{
var DrinkingUnderAge = true;
Console.WriteLine("Drinking Under Age: {0}", DrinkingUnderAge);
return 0;
}
}
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;
public class Exercise
{
static int Main()
{
var DrinkingUnderAge = true;
Console.WriteLine("Drinking Under Age: {0}", DrinkingUnderAge);
DrinkingUnderAge = false;
Console.WriteLine("Drinking Under Age: {0}", DrinkingUnderAge);
return 0;
}
}
This would produce:
Drinking Under Age: True Drinking Under Age: False Press any key to continue . . .
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;
public class Exercise
{
static int Main()
{
var 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);
return 0;
}
}
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 float 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 float Bathrooms;
public byte Stories;
public bool HasCarGarage;
public int YearBuilt;
public double Value;
}
public class Program
{
static int Main()
{
var Condominium = new
{
HasCarGarage = false,
YearBuilt = 2002,
Bathrooms = 1.5F,
Stories = 18,
Value = 155825,
Bedrooms = 2,
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);
return 0;
}
}
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.
To compare two variables for equality, C# uses the == operator. The formula used is:
Value1 == Value2
The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false.

Most of the comparisons performed in C# will be applied to conditional statements. The result of a comparison can also be assigned to a variable. To store the result of a comparison, you should include the comparison operation between parentheses. Here is an example:
using System;
public class Exercise
{
static int Main()
{
var Value1 = 15;
var Value2 = 24;
Console.Write("Value 1 = ");
Console.WriteLine(Value1);
Console.Write("Value 2 = ");
Console.WriteLine(Value2);
Console.Write("Comparison of Value1 == 15 produces ");
Console.WriteLine(Value1 == 15);
return 0;
}
}
This would produce:
Value 1 = 15 Value 2 = 24 Comparison of Value1 == 15 produces True
It is important to make a distinction between the assignment "=" and the logical equality operator "==". The first is used to give a new value to a variable, as in Number = 244. The operand on the left side of = must always be a variable and never a constant. The == operator is never used to assign a value; this would cause an error. The == operator is used only to compare to values. The operands on both sides of == can be variables, constants, or one can be a variable while the other is a constant. If you use one operator in place of the other, you would receive an error when you compile the program.
|
The Logical Not Operator ! |
When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. C# considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is:
!Value
There are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator is to check the state of a variable.
To nullify a variable, you can write the exclamation point to its left. Here is an example:
using System;
public class Exercise
{
static int Main()
{
bool HasAirCondition = true;
bool DoesIt;
Console.Write("HasAirCondition = ");
Console.WriteLine(HasAirCondition);
DoesIt = !HasAirCondition;
Console.Write("DoesIt = ");
Console.WriteLine(DoesIt);
return 0;
}
}
This would produce:
HasAirCondition = True DoesIt = False
When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it.
|
The Inequality Operator != |
As opposed to Equality, C# provides another operator used to compare two values for inequality. This operation uses a combination of equality and logical not operators. It combines the logical not ! and a simplified == to produce !=. Its syntax is:
Value1 != Value2
The != is a binary operator (like all logical operator except the logical not, which is a unary operator) that is used to compare two values. The values can come from two variables as in Variable1 != Variable2. Upon comparing the values, if both variables hold different values, the comparison produces a true or positive value. Otherwise, the comparison renders false or a null value:

Here is an example:
using System;
public class Exercise
{
static int Main()
{
var Value1 = 212;
var Value2 = -46;
var Value3 = (Value1 != Value2);
Console.Write("Value1 = ");
Console.WriteLine(Value1);
Console.Write("Value2 = ");
Console.WriteLine(Value2);
Console.Write("Value3 = ");
Console.Write(Value3);
Console.WriteLine();
return 0;
}
}
The inequality is obviously the opposite of the equality.
|
The Comparison for a Lower Value < |
To find out whether one value is lower than another, use the < operator. Its syntax is:
Value1 < Value2
The value held by Value1 is compared to that of Value2. As
it would be done with other operations, the comparison can be made between two
variables, as in Variable1 < Variable2. If the value held by Variable1 is lower
than that of Variable2, the comparison produces a true or positive result.

Here is an example:
using System;
public class Exercise
{
static int Main()
{
var Value1 = 15;
var Value2 = (Value1 < 24);
Console.Write("Value 1 = ");
Console.WriteLine(Value1);
Console.Write("Value 2 = ");
Console.WriteLine(Value2);
Console.WriteLine();
return 0;
}
}
This would produce:
Value 1 = 15 Value 2 = True
|
Combining Equality and Lower Value <= |
The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is:
Value1 <= Value2
The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 hold the same value, result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.

Here is an example:
using System;
public class Exercise
{
static int Main()
{
var Value1 = 15;
var Value2 = (Value1 <= 24);
Console.Write("Value 1 = ");
Console.WriteLine(Value1);
Console.Write("Value 2 = ");
Console.WriteLine(Value2);
Console.WriteLine();
return 0;
}
}
This would produce:
Value 1 = 15 Value 2 = True
|
The Comparison for a Greater Value > |
When two values of the same type are distinct, one of them is usually higher than the other. C# provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its syntax is:
Value1 > Value2
Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value . Otherwise, the comparison renders false or null:

|
The Greater Than or Equal Operator >= |
The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is:
Value1 >= Value2
A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand,, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result:
Here is a summary table of the logical operators we have studied:
| Operator | Meaning | Example | Opposite |
| == | Equality to | a == b | != |
| != | Not equal to | 12 != 7 | == |
| < | Less than | 25 < 84 | >= |
| <= | Less than or equal to | Cab <= Tab | > |
| > | Greater than | 248 > 55 | <= |
| >= | Greater than or equal to | Val1 >= Val2 | < |
|
Logically Incrementing or Decrementing a Value |
|
Incrementing a Variable |
We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting such numbers, we are simply adding 1 to a number in order to get the next number in the range. The simplest technique of incrementing a value consists of adding 1 to it. After adding 1, the value or the variable is (permanently) modified and the variable would hold the new value. This is illustrated in the following example:
// This program studies value incrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of incrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Value = Value + 1;
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This would produce:
Techniques of incrementing a value Value = 12 Value = 13
C# provides a special operator that takes care of this operation. The operator is called the increment operator and is represented by ++. Instead of writing Value = Value + 1, you can write Value++ and you would get the same result. The above program can be re-written as follows:
// This program studies value incrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of incrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Value++;
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
The ++ is a unary operator because it operates on only one variable. It is used to modify the value of the variable by adding 1 to it. Every time the Value++ is executed, the compiler takes the previous value of the variable, adds 1 to it, and the variable holds the incremented value:
// This program studies value incrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of incrementing a value");
Value++;
Console.Write("Value = ");
Console.WriteLine(Value);
Value++;
Console.Write("Value = ");
Console.WriteLine(Value);
Value++;
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This would produce:
Techniques of incrementing a value Value = 13 Value = 14 Value = 15
|
Pre and Post-Increment |
When using the ++ operator, the position of the operator with regard to the variable it is modifying can be significant. To increment the value of the variable before re-using it, you should position the operator on the left of the variable:
// This program studies value incrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of incrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Console.Write("Value = ");
Console.WriteLine(++Value);
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This would produce:
Techniques of incrementing a value Value = 12 Value = 13 Value = 13
When writing ++Value, the value of the variable is incremented before being called. On the other hand, if you want to first use a variable, then increment it, in other words, if you want to increment the variable after calling it, position the increment operator on the right side of the variable:
// This program studies value incrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of incrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Console.Write("Value = ");
Console.WriteLine(Value++);
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This would produce:
Techniques of incrementing a value Value = 12 Value = 12 Value = 13
|
Decrementing a Value |
When counting numbers backward, such as 8, 7, 6, 5, etc, we are in fact subtracting 1 from a value in order to get the lesser value. This operation is referred to as decrementing a value. This operation works as if a value is decremented by 1, as in Value = Value – 1:
// This program studies value decrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of decrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Value = Value - 1;
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This would produce:
Techniques of decrementing a value Value = 12 Value = 11
As done to increment, C# provides a quicker way of subtracting 1 from a value. This is done using the decrement operator, that is --. To use the decrement operator, type –- on the left or the right side of the variable when this operation is desired. Using the decrement operator, the above program could be written:
// This program studies value decrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of decrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Value--;
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
|
Pre Decrementing a Value |
Once again, the position of the operator can be important. If you want to decrement the variable before calling it, position the decrement operator on the left side of the operand. This is illustrated in the following program:
// This program studies value decrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of decrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Console.Write("Value = ");
Console.WriteLine(--Value);
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This would produce:
Techniques of decrementing a value Value = 12 Value = 11 Value = 11
If you plan to decrement a variable only after it has been accessed, position the operator on the right side of the variable. Here is an example:
// This program studies value decrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12;
Console.WriteLine("Techniques of decrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Console.Write("Value = ");
Console.WriteLine(Value--);
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This would produce:
Techniques of decrementing a value Value = 12 Value = 12 Value = 11
|
Techniques of Incrementing and Decrementing a Variable |
It is not unusual to add or subtract a constant value to or from a variable. All you have to do is to declare another variable that would hold the new value. Here is an example:
// This program studies value incrementing and decrementing
using System;
public class Exercise
{
static int Main()
{
double Value = 12.75;
double NewValue;
Console.WriteLine("Techniques of incrementing and decrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
NewValue = Value + 2.42;
Console.Write("Value = ");
Console.WriteLine(NewValue);
return 0;
}
}
This would produce:
Techniques of incrementing and decrementing a value Value = 12.75 Value = 15.17
The above technique requires that you use an extra variable in your application. The advantage is that each value can hold its own value although the value of the second variable depends on whatever would happen to the original or source variable.
Sometimes in your program you will not need to keep the original value of the source variable. You may want to permanently modify the value that a variable is holding. In this case you can perform the addition operation directly on the variable by adding the desired value to the variable. This operation modifies whatever value a variable is holding and does not need an additional variable.
To add a value to a variable and change the value that the variable is holding, you can combine the assignment “=” and the addition “+” operators to produce a new operator as +=
Here is an example:
// This program studies value incrementing and decrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12.75;
Console.WriteLine("Techniques of incrementing and decrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Value += 2.42;
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This program produces the same result as the previous. To decrement the value of a variable, instead of the addition, use the subtraction and apply the same technique. In the above program, the variable can have its value decremented by combining the assignment and the subtraction operations on the variable. This is done with the -= operator. Here is an example:
// This program studies value incrementing and decrementing
using System;
public class Exercise
{
static int Main()
{
var Value = 12.75;
Console.WriteLine("Techniques of incrementing and decrementing a value");
Console.Write("Value = ");
Console.WriteLine(Value);
Value -= 2.42;
Console.Write("Value = ");
Console.WriteLine(Value);
return 0;
}
}
This would produce:
Techniques of incrementing and decrementing a value Value = 12.75 Value = 10.33
|
|
||
| Previous | Copyright © 2008 Yevol | Next |
|
|
||