If is a conditional struct. It means that it must control the behavior of some actions based on some condition. For example: you have a variable with the value of 5. You want to print a certain message if the value changes.
The if statement/struct looks like this:
if ( condition ) action to be takenThe condition can take two values: true or false, and only if it is true, the actions to be taken will proceed. If false, nothing is done. Note that when you want more than one action to be taken, you must put brackets, like this:
if ( condition ) { actions to be taken }
Let's write a small sample: this application ask the user for a name, and if the name is Mono, it will print a welcome message; if not, it will print a different welcome message.
// // A *if* sample - if-test.cs // using System; public class MonoTutorial { public static void Main () { // The string containing the name string name; // Ask for the user name Console.WriteLine("Hello, user. Write your name: "); // Capture the user input name = Console.ReadLine(); // If the name was "Mono", write a welcome message if ( name == "Mono" ) Console.WriteLine("Welcome, Mono Man !"); } }
Save it as if-test.cs, and compile:
mcs if-test.csAnd run it:
mono if-test.exe
Now let's appreciate two behaviors of our application ( the words in italics are the user input) :
$ mono if-test.exe Hello, user. Write your name: Carlos $ mono if-test.exe Hello, user. Write your name: Mono Welcome, Mono Man !
Note that only if the user writes "Mono" when asked for a name, it shows a welcome message; if not, it does nothing.