Home

Conditional Statements

 

Introduction to Conditional Statements

 

Introduction

Imagine you are writing a program for the Motor Vehicle Administration. When processing a driver's license, you want to be able to ask an applicant if he or she wants to be an organ donor. This section of the program can appear as follows:

using System;

class Exercise
{
	static void Main()
	{
		string Answer;

		Console.Write("Are you willing to be an organ donor? ");
		Answer = Console.ReadLine();

		return 0;
	}
}

The possible answers to this question are y, yes, Y, Yes, YES, n, N, no, No, NO, I don’t know, It depends, Why are you asking?, What do you mean?, What kind of organ are you referring to? What kind of person would possibly want my organ? Are you planning to sell my body parts?, etc. When you ask this type of question, make sure you let the applicant know that this is a simple question expecting a simple answer. For example, the above question can be formulated as follows:

using System;

class Exercise
{
	static void Main()
	{
		string Answer;

		Console.Write("Are you willing to be an organ donor (y=Yes/n=No)? ");
		Answer = Console.ReadLine();

		return 0;
	}
}

This time, the applicant knows that the expected answers are simply y for Yes or n for No.

 

Practical LearningPractical Learning: Introducing Conditional Statements

  1. Start Microsoft Visual C# or Visual Studio .NET
  2. On the main menu, click File -> New -> Project
  3. If necessary, in the Project Types list of the New Project dialog box, click Visual C# Projects
  4. In the Templates list, click Empty Project
  5. In the Name text box, replace the name with MVD1 and specify the desired path in the Location
  6. Click OK
  7. To create a source file for the project, on the main menu, click Project -> Add New Item...
  8. In the Add New Item dialog box, in the Templates list, click Code File
  9. In the Name text box, delete the suggested name and replace it with Exercise
  10. Click Open
  11. In the empty file, type the following:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	class Exercise
    	{
    		static void Main()
    		{
    			string FirstName, LastName;
    	
    			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("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    			Console.WriteLine("Full Name: {0} {1}\n", FirstName, LastName);
    		}
    	}
    }
  12. To execute the application, on the main menu, click Debug -> Start Without Debugging
  13. Return to Visual C#

Boolean Variables

A variable is referred to as Boolean if it is meant to carry only one of two logical values stated as true or false. For this reason, such a variable is used only when testing conditions or when dealing with conditional statements.

To declare a Boolean variable, you can use the bool keyword. Here is an example of declaring a Boolean variable:

bool TheStudentIsHungry;

After declaring a Boolean variable, you can give it a value by assigning it a true or false value. Here is an example:

using System;

class ObjectName
{
	static void Main()
	{
		bool TheStudentIsHungry;

		TheStudentIsHungry = true;
		Console.Write("The Student Is Hungry expression is: ");
		Console.WriteLine(TheStudentIsHungry);
		TheStudentIsHungry = false;
		Console.Write("The Student Is Hungry expression is: ");
		Console.WriteLine(TheStudentIsHungry);
	}
}

This would produce:

The Student Is Hungry expression is: True
The Student Is Hungry expression is: False

You can also give its first value to a variable when declaring it. In this case, the above variable can be declared and initialized as follows:

bool TheStudentIsHungry = true;
 

Practical Learning Practical Learning: Using a Boolean Variable

  1. To use an example of a Boolean variable, change the file as follows:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	class Exercise
    	{
    		static void Main()
    		{
    			string FirstName, LastName;
    			bool WillingToBeAnOrganDonor;
    	
    			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(True=Yes/False=No)? ");
    			WillingToBeAnOrganDonor = bool.Parse(Console.ReadLine());
    
    			Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    			Console.WriteLine("Full Name: {0} {1}", FirstName, LastName);
    			Console.WriteLine("Organ Donor? {0}", WillingToBeAnOrganDonor);
    
    			return 0;
    		}
    	}
    }
  2. Execute the application. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Ahmed
    Last Name:  Kouakou
    Are you willing to be an Organ Donor(True=Yes/False=No)? True
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name:   Ahmed Kouakou
    Organ Donor? True
  3. Return to Visual C#
 

Formulations of Conditional Statements

 

if a Condition is True

One of the most regularly performed operations on a program consists of checking that a condition is true or false. When something is true, you may act one way. If it is false, you act another way. A condition that a program checks must be clearly formulated in a statement, following specific rules. The statement can come from you or from the computer itself. Examples of statements are:

  • "You are 12 years old"
  • "It is raining outside"
  • You live in Sydney"

One of the comparisons the computer performs is to find out if a statement is true (in reality, programmers (like you) write these statements and the computer only follows your logic). If a statement is true, the computer acts on a subsequent instruction.

The comparison using the if statement is used to check whether a condition is true or false. The syntax to use it is:

if(Condition) Statement;

If the Condition is true, then the compiler would execute the Statement. The compiler ignores anything else:

Flowchart - If
 

If the statement to execute is (very) short, you can write it on the same line with the condition that is being checked.

Consider a program that is asking a user to answer Yes or No to a question such as "Are you ready to provide your credit card number?". A source file of such a program could look like this:

 
using System;

class NewProject
{
    static void Main()
    {
	char Answer;
	string Ans;
	
	// Request the availability of a credit card from the user
	Console.Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	Ans = Console.ReadLine();
	Answer = char.Parse(Ans);

	// Since the user is ready, let's process the credit card transaction
	if(Answer == '1') Console.WriteLine("\nNow we will get your credit card information.");
    }
}

You can write the if condition and the statement on different lines; this makes your program easier to read. The above code could be written as follows:

using System;

class NewProject
{
	static void Main()
	{
		char Answer;
		string Ans;
	
		// Request the availability of a credit card from the user
		Console.Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
		Ans = Console.ReadLine();
		Answer = char.Parse(Ans);

		// Since the user is ready, let's process the credit card transaction
		if(Answer == '1')
			Console.WriteLine("\nNow we will get your credit card information.");

	}
}

You can also write the statement on its own line if the statement is too long to fit on the same line with the condition.

Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket “{“ and a closing curly bracket “}”. Here is an example:

using System;

class NewProject
{
	static void Main()
	{
		char Answer;
		string Ans, CreditCardNumber;
	
		// Request the availability of a credit card from the user
		Console.Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
		Ans = Console.ReadLine();
		Answer = char.Parse(Ans);

		// Since the user is ready, let's process the credit card transaction
		if(Answer == '1')
		{
			Console.WriteLine("Now we will get your credit card information.");
			Console.Write("Please enter your credit card number without spaces: ");
			CreditCardNumber = Console.ReadLine();
		}
	}
}

If you omit the brackets, only the statement that immediately follows the condition would be executed.

 

Practical LearningPractical Learning: Using if

  1. To state an if condition, change the program as follows:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	class Exercise
    	{
    		static void Main()
    		{
    			string FirstName, LastName;
    			string OrganDonorAnswer;
    	
    			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("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    			Console.WriteLine("Full Name:   {0} {1}", FirstName, LastName);
    			Console.Write("Organ Donor? ");
    			if( OrganDonorAnswer == "1" ) Console.WriteLine("Yes");
    		}
    	}
    }
  2. Execute the application. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Catherine
    Last Name:  Wallington
    Are you willing to be an Organ Donor(1=Yes/0=No)? 1
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name:   Catherine Wallington
    Organ Donor? Yes
  3. Return to Visual C#

Otherwise: if…else

The if condition is used to check one possibility and ignore anything else. Usually, other conditions should be considered. In this case, you can use more than one if statement. For example, on a program that asks a user to answer Yes or No, although the positive answer is the most expected, it is important to offer an alternate statement in case the user provides another answer. Here is an example:

using System;

class NewProject
{
	static void Main()
	{
		char Answer;
		string Ans;
	
		// Request the availability of a credit card from the user
		Console.Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
		Ans = Console.ReadLine();
		Answer = char.Parse(Ans);

		if( Answer == 'y' ) // First Condition
		{
			Console.WriteLine("\nThis job involves a high level of self-control.");
			Console.WriteLine("We will get back to you.\n");
		}
		if( Answer == 'n' ) // Second Condition
			Console.Write("\nYou are hired!\n");
	}
}

Here is an example of running the program:

Do you consider yourself a hot-tempered individual(y=Yes/n=No)? y

This job involves a high level of self-control.
We will get back to you.

Press any key to continue

The problem with the above program is that the second if is not an alternative to the first, it is just another condition that the program has to check and execute after executing the first. On that program, if the user provides y as the answer to the question, the compiler would execute the content of its statement and the compiler would execute the second if condition.

You can also ask the compiler to check a condition; if that condition is true, the compiler will execute the intended statement. Otherwise, the compiler would execute alternate statement. This is performed using the syntax:

if(Condition)
    Statement1;
else
    Statement2;
Flowchart

The above program would better be written as:

using System;

class NewProject
{
	static void Main()
	{
		char Answer;
		string Ans;
	
		// Request the availability of a credit card from the user
		Console.Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
		Ans = Console.ReadLine();
		Answer = char.Parse(Ans);

		if( Answer == 'y' ) // First Condition
		{
			Console.WriteLine("\nThis job involves a high level of self-control.");
			Console.WriteLine("We will get back to you.\n");
		}
		else // Second Condition
			Console.Write("\nYou are hired!\n");
	}
}

 

 

Practical LearningPractical Learning: Using if...else

  1. Make the following changes to the file:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	class Exercise
    	{
    		static void Main()
    		{
    			string FirstName, LastName;
    			string OrganDonorAnswer;
    			char Gender;
    	
    			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("Gender(F=Female/M=Male): ");
    			Gender = char.Parse(Console.ReadLine());
    			Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    			OrganDonorAnswer = Console.ReadLine();
    
    			Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    			Console.WriteLine("Full Name:   {0} {1}", FirstName, LastName);
    			Console.WriteLine("Gender:         {0}", Gender);
    			Console.Write("Organ Donor? ");
    			if( OrganDonorAnswer == "1" )
    				Console.WriteLine("Yes");
    			else if( OrganDonorAnswer == "0" )
    				Console.WriteLine("No");
    		}
    	}
    }
  2. Execute the application and test it twice, once with 1 to the question, then with 0 to the last question
  3. Return to Visual C#

The Ternary Operator (?:)

The conditional operator behaves like a simple if…else statement. Its syntax is:

Condition ? Statement1 : Statement2;

The compiler would first test the Condition. If the Condition is true, then it would execute Statement1, otherwise it would execute Statement2. When you request two numbers from the user and would like to compare them, the following program would do find out which one of both numbers is higher. The comparison is performed using the conditional operator:

using System;

class NewProject
{
	static void Main()
	{
		int Number1, Number2, Maximum;
		string Num1, Num2;
	
		Console.Write("Enter first numbers: ");
		Num1 = Console.ReadLine();
		Console.Write("Enter second numbers: ");
		Num2 = Console.ReadLine();
		
		Number1 = int.Parse(Num1);
		Number2 = int.Parse(Num2);
	
		Maximum = (Number1 < Number2) ? Number2 : Number1;
	
		Console.Write("\nThe maximum of ");
		Console.Write(Number1);
		Console.Write(" and ");
		Console.Write(Number2);
		Console.Write(" is ");
		Console.WriteLine(Maximum);
	
		Console.WriteLine();
	}
}

Here is an example of running the program:

Enter first numbers: 244
Enter second numbers: 68

The maximum of 244 and 68 is 244

Practical LearningPractical Learning: Using the Ternary Operator

  1. To use the ternary operator, change the file as follows:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	class Exercise
    	{
    		static void Main()
    		{
    			string FirstName, LastName;
    			string OrganDonorAnswer;
    			char Gender;
    	
    			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("Gender(F=Female/M=Male): ");
    			Gender = char.Parse(Console.ReadLine());
    			Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    			OrganDonorAnswer = Console.ReadLine();
    
    			Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    			Console.WriteLine("Full Name:   {0} {1}", FirstName, LastName);
    			Console.WriteLine("Gender:      {0}", Gender);
    			Console.Write("Organ Donor? ");
    			Console.WriteLine(OrganDonorAnswer == "1" ? "Yes" : "No");
    		}
    	}
    }
  2. Execute the application to test it 
  3. Return to Visual C#

Conditional Statements: if…else if and if…else if…else

The previous conditional formula is used to execute one of two alternatives. Sometimes, your program will need to check many more statements than that. The syntax for such a situation is:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;

An alternative syntax would add the last else as follows:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else
    Statement-n;
if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else if(Condition3)
    Statement3;
else
    Statement-n;
 

The compiler will check the first condition. If Condition1 is true, it will execute Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means that you can include as many conditions as you see fit using the else if statement. After examining all the known possible conditions, if you still think that there might be an unexpected condition, you can use the optional single else.

A program we previously wrote was considering that any answer other than y was negative. It would be more professional to consider a negative answer because the program anticipated one. Therefore, here is a better version of the program:

using System;

class NewProject
{
	static void Main()
	{
		char Answer;
		string Ans;
	
		// Request the availability of a credit card from the user
		Console.Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
		Ans = Console.ReadLine();
		Answer = char.Parse(Ans);

		if( Answer == 'y' ) // First Condition
		{
			Console.WriteLine("\nThis job involves a high level of self-control.");
			Console.WriteLine("We will get back to you.\n");
		}
		else if( Answer == 'n' ) // Alternative
			Console.Write("\nYou are hired!\n");
		else
			Console.Write("\nThat's not a valid answer!\n");
	}
}

You can also use the ternary operator recursively to process an if...else if condition.

 

Practical LearningPractical Learning: Using if...else if

  1. Change the file as follows:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	class Exercise
    	{
    		static void Main()
    		{
    			string FirstName, LastName;
    			string OrganDonorAnswer;
    			char Sex;
    			string Gender;
    	
    			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("Gender(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' )
    				Gender = "Female";
    			else if( Sex == 'F' )
    				Gender = "Female";
    			else if( Sex == 'm' )
    				Gender = "Male";
    			else if( Sex == 'M' )
    				Gender = "Male";
    			else
    				Gender = "Unknown";
    
    			Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    			Console.WriteLine("Full Name:   {0} {1}", FirstName, LastName);
    			Console.WriteLine("Gender:      {0}", Gender);
    			Console.Write("Organ Donor? ");
    			Console.WriteLine(OrganDonorAnswer == "1" ? "Yes" : "No");
    		}
    	}
    }
  2. Execute the application. Here is an example:
     
  3. Return to Visual C#
  4. To use a multi-ternary operator as if...else if, change the file as follows:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	class Exercise
    	{
    		static void Main()
    		{
    			string FirstName, LastName;
    			string OrganDonorAnswer;
    			char Sex;
    			string Gender;
    	
    			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("Gender(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' )
    				Gender = "Female";
    			else if( Sex == 'F' )
    				Gender = "Female";
    			else if( Sex == 'm' )
    				Gender = "Male";
    			else if( Sex == 'M' )
    				Gender = "Male";
    			else
    				Gender = "Unknown";
    			Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    			Console.WriteLine("Full Name:   {0} {1}", FirstName, LastName);
    			Console.WriteLine("Gender:      {0}", Gender);
    			Console.Write("Organ Donor? ");
    	Console.WriteLine(OrganDonorAnswer == "1" ? "Yes" : (OrganDonorAnswer == "0" ? "No" : "Invalid Answer"));
    		}
    	}
    }
  5. Execute the application 
  6. Return to Visual C#

The switch Statement

When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: “{“ to “}”. The syntax of the switch statement is:

switch(Expression)
{
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
}
In C++, you can omit the break keyword in a case. This creates the "fall through" effect as follows: after code executes in a case, if nothing "stops" it, the execution continues to the next case. This has caused problems and confusing execution in the past in some C++ programs. To avoid it, C# requires code interruption at the end of every case. This interruption is done using the break keyword.

The expression to examine in a case statement is an integer. Since a member of an enumerator (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:

using System;

class NewProject
{
	static void Main()
	{
		int Number;
		string Nbr;
	
		Console.Write("Type a number between 1 and 3: ");
		Nbr = Console.ReadLine();
		Number = int.Parse(Nbr);
	
		switch(Number)
		{
			case 1:
				Console.Write("\nYou typed 1.");
				break;
			case 2:
				Console.Write("\nYou typed 2.");
				break;
			case 3:
				Console.Write("\nYou typed 3.");
				break;
		}
		
		Console.WriteLine();
	}
}

When establishing the possible outcomes that the switch statement should consider, at times there will be possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:

switch(Expression)
{
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
    default:
         Other-Possibility;
	break;
}
In C++, the default section doesn't need a break keyword because it is the last. In C#, every case and the default section must have its own exit mechanism, which is taken care of by a break keyword.

Therefore another version of the program above would be

using System;

class NewProject
{
	static void Main()
	{
		int Number;
		string Nbr;
	
		Console.Write("Type a number between 1 and 3: ");
		Nbr = Console.ReadLine();
		Number = int.Parse(Nbr);
	
		switch(Number)
		{
			case 1:
				Console.Write("\nYou typed 1.");
				break;
			case 2:
				Console.Write("\nYou typed 2.");
				break;
			case 3:
				Console.Write("\nYou typed 3.");
				break;
			default:
				Console.Write(Number);
				Console.WriteLine(" is out of the requested range.");
				break;
		}
		
		Console.WriteLine();
	}
}

Here is an example of running the program:

Type a number between 1 and 3: 8
8 is out of the requested range.

The switch statement can be used to combine cases executes as one. To do this, you can type two or more cases together. Here is an example:

using System;

class NewProject
{
	static void Main()
	{
		char Letter;

		Console.Write("Type a letter: ");
		string Ltr = Console.ReadLine();
		Letter = char.Parse(Ltr);

		switch(Letter)
		{
			case 'a':
			case 'A':
			case 'e':
			case 'E':
			case 'i':
			case 'I':
			case 'o':
			case 'O':
			case 'u':
			case 'U':
				Console.WriteLine("The letter you typed, {0}, is a vowel", Letter);
				break;

			case 'b':case 'c':case 'd':case 'f':case 'g':case 'h':case 'j':
			case 'k':case 'l':case 'm':case 'n':case 'p':case 'q':case 'r':
			case 's':case 't':case 'v':case 'w':case 'x':case 'y':case 'z':
				Console.WriteLine("{0} is a lowercase consonant", Letter);
				break;

			case 'B':case 'C':case 'D':case 'F':case 'G':case 'H':case 'J':
			case 'K':case 'L':case 'M':case 'N':case 'P':case 'Q':case 'R':
			case 'S':case 'T':case 'V':case 'W':case 'X':case 'Y':case 'Z':
				Console.WriteLine("{0} is a consonant in uppercase", Letter);
				break;

			default:
				Console.Write("The symbol ");
				Console.WriteLine("{0} is not an alphabetical letter", Letter);
				break;
		}

		return 0;
	}
}

This would produce:

Type a letter: g
g is a lowercase consonant
 

Practical LearningPractical Learning: Using a switch Statement

  1. Change the file as follows:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	class Exercise
    	{
    		static void Main()
    		{
    			string FirstName, LastName;
    			string OrganDonorAnswer;
    			char Sex;
    			string Gender;
    			char DLClass;
    	
    			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("Gender(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' )
    				Gender = "Female";
    			else if( Sex == 'F' )
    				Gender = "Female";
    			else if( Sex == 'm' )
    				Gender = "Male";
    			else if( Sex == 'M' )
    				Gender = "Male";
    			else
    				Gender = "Unknown";
    			Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    			Console.WriteLine("Full Name:   {0} {1}", FirstName, LastName);
    			Console.WriteLine("Gender:      {0}", Gender);
    
    			switch(DLClass)
    			{
    				case 'a':
    				case 'A':
    					Console.WriteLine("Class:       A");
    					break;
    				case 'b':
    				case 'B':
    					Console.WriteLine("Class:       B");
    					break;
    				case 'c':
    				case 'C':
    					Console.WriteLine("Class:       C");
    					break;
    				case 'k':
    				case 'K':
    					Console.WriteLine("Class:       K");
    					break;
    				case 'm':
    				case 'M':
    					Console.WriteLine("Class:       M");
    					break;
    				default:
    					Console.WriteLine("Class:       Unknown");
    					break;
    			}
    
    			Console.Write("Organ Donor? ");
    			Console.WriteLine(OrganDonorAnswer == "1" ? "Yes" : (OrganDonorAnswer == "0" ? "No" : "Invalid Answer"));
    		}
    	}
    }
  2. Execute the application to test it. Here is an example:
     
  3. Return to Visual C#

 

Enumerators

An enumerator is a list of natural numeric values with each value represented by a name. Enumerators are highly useful in conditional statements because they allow using recognizable names to identify confusing numbers.

To create an enumerator, use the enum keyword followed by a name. The values, called members of the enumerator, are included between an opening curly bracket and the list ends with a closing curly bracket. Here is an example:

enum MemberCategories { Teen, Adult, Senior }

As stated already, each member of the enumerator holds a value of a natural number, such as 0, 4, 12, 25, etc. In C#, an enumerator cannot hold character values (of type char). After creating an enumerator, you can declare a variable from it. For example, you can declare a variable of a MemberCategories type as follows:

using System;

class BookClub
{
	enum MemberCategories { Teen, Adult, Senior }

	static void Main()
	{
		MemberCategories MbrCat;
	}
}

After declaring such a variable, to initialize it, specify which member of the enumerator would be given to it. You should only assign a known member of the enumerator. To do this, on the right side of the assignment operator, type the name of the enumerator, followed by the period operator, and followed by the member whose value you want to assign. Here is an example:

using System;

class BookClub
{
	enum MemberCategories { Teen, Adult, Senior }

	static void Main()
	{
		MemberCategories MbrCat = MemberCategories.Adult;
	}
}

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;

class BookClub
{
	enum MemberCategories { Teen, Adult, Senior }

	static void Main()
	{
		MemberCategories MbrCat = MemberCategories.Adult;
		Console.WriteLine(MbrCat);
	}
}

This would produce:

mcAdult

As mentioned already, an enumerator 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. For example, on the MemberCategories 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 enumerator to have a value of 5. To do this, use the assignment operator "=" to give the desired value. The enumerator would be:

enum MemberCategories { Teen=5, Adult, Senior };

In this case, Teen now would 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 enumerator. Here is an example:

enum MemberCategories { Teen=3, Adult=8, Senior };

In this case, Senior would have a value of 9.

An enumerator is very useful in a switch statement where it can be used case sections. An advantage of using an enumerator is its ability to be more explicit than a regular integer. To use an enumerator, define it and list each one of its members for the case that applies. Remember that, by default, the members of an enumerator are counted with the first member having a value of 0, the second is 1, etc. Here is an example of a switch statement that uses an enumerator.

using System;

class NewProject
{
	enum EmploymentStatus { FullTime, PartTime, Contractor, NotSpecified }

	static void Main()
	{
		int EmplStatus;

		Console.WriteLine("Employee's Contract Status: ");
		Console.WriteLine("0 - Full Time | 1 - Part Time");
		Console.WriteLine("2 - Contractor | 3 - Other");
		Console.Write("Status: ");
		string Status = Console.ReadLine();
		EmplStatus = int.Parse(Status);
		
		Console.WriteLine();

		switch( (EmploymentStatus)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");
				break;

			case EmploymentStatus.PartTime:
				Console.WriteLine("Employment Status: Part Time");
				Console.WriteLine("Employee's Benefits: Sick Leave");
				Console.WriteLine(" Maternal Leave");
				break;

			case EmploymentStatus.Contractor:
				Console.WriteLine("Employment Status: Contractor");
				Console.WriteLine("Employee's Benefits: None");
				break;

			case EmploymentStatus.NotSpecified:
				Console.WriteLine("Employment Status: Other");
				Console.WriteLine("Status Not Specified");
				break;

			default:
				Console.WriteLine("Unknown Status\n");
				break;
		}

		return 0;
	}
}

Here is an example of running the program:

Employee's Contract Status:
0 - Full Time | 1 - Part Time
2 - Contractor | 3 - Other
Status: 1

Employment Status: Part Time
Employee's Benefits: Sick Leave
 Maternal Leave
 

Practical Learning Practical Learning: Using an Enumerator

  1. To use an enumerator, change the contents of the file as follows:
     
    using System;
    
    namespace MotorVehicleDivision
    {
    	enum TypeOfApplication
    	{
    		NewDriversLicense = 1,
    		UpgradeFromIDCard,
    		TransferFromAnotherState
    	}
    
    	class Exercise
    	{
    		static void Main()
    		{
    			TypeOfApplication AppType;
    			string FirstName, LastName;
    			string OrganDonorAnswer;
    			char Sex;
    			string Gender;
    			char DLClass;
    	
    			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: ");
    			int type = int.Parse(Console.ReadLine());
    			Console.Write("First Name: ");
    			FirstName = Console.ReadLine();
    			Console.Write("Last Name:  ");
    			LastName = Console.ReadLine();
    			Console.Write("Gender(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' )
    				Gender = "Female";
    			else if( Sex == 'F' )
    				Gender = "Female";
    			else if( Sex == 'm' )
    				Gender = "Male";
    			else if( Sex == 'M' )
    				Gender = "Male";
    			else
    				Gender = "Unknown";
    			Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    			Console.WriteLine(" --- Driver's License Information ---");
    
    			AppType = (TypeOfApplication)type;
    			Console.Write("Type of Application: ");
    			switch(AppType)
    			{
    				case TypeOfApplication.NewDriversLicense:
    					Console.WriteLine("New Driver's License");
    					break;
    				case TypeOfApplication.UpgradeFromIDCard:
    					Console.WriteLine("Upgrade From Identity Card");
    					break;
    				case TypeOfApplication.TransferFromAnotherState:
    					Console.WriteLine("Transfer From Another State");
    					break;
    				default:
    					Console.WriteLine("Not Specified");
    					break;
    			}
    			Console.WriteLine("Full Name:   {0} {1}", FirstName, LastName);
    			Console.WriteLine("Gender:      {0}", Gender);
    
    			switch(DLClass)
    			{
    				case 'a':
    				case 'A':
    					Console.WriteLine("Class:       A");
    					break;
    				case 'b':
    				case 'B':
    					Console.WriteLine("Class:       B");
    					break;
    				case 'c':
    				case 'C':
    					Console.WriteLine("Class:       C");
    					break;
    				case 'k':
    				case 'K':
    					Console.WriteLine("Class:       K");
    					break;
    				case 'm':
    				case 'M':
    					Console.WriteLine("Class:       M");
    					break;
    				default:
    					Console.WriteLine("Class:       Unknown");
    					break;
    			}
    
    			Console.Write("Organ Donor? ");
    	Console.WriteLine(OrganDonorAnswer == "1" ? "Yes" : (OrganDonorAnswer == "0" ? "No" : "Invalid Answer"));
    		}
    	}
    }
  2. Save the file. Compile and execute it. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
     - Select the type of application -
    1 - Applying for a brand new Driver's License
    2 - Applicant already had an ID Card and is applying for a Driver's License
    3 - Applicant is transferring his/her Driver's License from another state
    Your Choice: 2
    First Name: Jeremy
    Last Name:  Lamant
    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: m
    Are you willing to be an Organ Donor(1=Yes/0=No)? 1
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Type of Application: Upgrade From Identity Card
    Full Name:   Jeremy Lamant
    Sex:         Male
    Class:       M
    Organ Donor? Yes
  3. Return to Visual C#
 

Previous Copyright © 2004-2005 FunctionX. Inc. Next