Control Structs

If/Else

Sometimes it is neccesary to take some actions if a condition is true, and, then, take some actions if not. For example: in the last example, the application prints a welcome message based on a condition. What about take an action for al anternative behavior?

Because of this we use the if/else control struct. It structure is:

 if ( condition )
	action to be taken
 else
	action to be taken if the condition was false
 

Let's write a small application that shows the behavior of a if/else control struct.

//
// If/else control struct
// ----------------------
// We will simule a user/password system
//
using System;

 class IfElseTest {

	public static void Main ()
	{

		string username, password;

		// Ask for the username and the password
		Console.WriteLine(":: Welcome to Mono System ::");
		
		Console.WriteLine(" Username: ");
		username = Console.ReadLine();

		Console.WriteLine("Password: ");
		password = Console.ReadLIne();

		// If the username is Mono
		// and the password is Handbook
		// simulate a succesful login
		if ( username == "Mono" && password == "Handbook" )
			Console.WriteLine(" Succesful login. You are in !");
		else 
			Console.WriteLine(" Sorry. Your login or password were wrong");
		

	}

 }

Pay attention on the bold words. The reserved keyword else marks the begin of this complementary struct. So, after the action(s) to be taken, goes the else keyword, and then, the action(s) to be taken if the condition was false/unsatisfied. In this case, we print a error message. Note the && operator, that reviews if both conditions are true, and if not, the entire condition becomes false.

Save, compile and run it. If everything went perfect, you should be able to probe the next behaviors on your application:

$ mono if-else.exe
:: Welcome to Mono System ::
Username: Carlos
Password: Handbook

Sorry. Your login or password were wrong

$ mono if-else.exe
:: Welcome to Mono System ::
Username: Mono
Password: Carlos

Sorry. Your login or password were wrong

$ mono if-else.exe
:: Welcome to Mono System ::
Username: Mono
Password: Handbook

Succesful login. You are in !

And yes, you can use the brackets for many actions, in you if section and in your else section.