C Sharp

The if Statement

The if statement executes one or more statements if the expression being evaluated is true. The if statement's syntax follows-the square brackets denote the optional use of the else statement (which we'll cover shortly): -

if (expression)
    statement1
[else
    statement2]

Here, expression is any test that produces a Boolean result. If expression results in true, control is passed to statement1. If the result is false and an else clause exists, control is passed to statement2. Also note that statement1 and statement2 can consist of a single statement terminated by a semicolon (known as a simple statement) or of multiple statements enclosed in braces (a compound statement). The following illustrates a compound statement being used if expression1 resolves to true: -

if (expression1)
{
    statement1
    statement2
}

In the following example, the application requests that the user type in a number between 1 and 10. A random number is then generated, and the user is told whether the number they picked matches the random number. This simple example illustrates how to use the if statement in C#.

using System;
class IfTest1App
{
    const int MAX = 10;
    public static void Main()
    {
        Console.Write("Guess a number between 1 and {0}...", MAX);
        string inputString = Console.ReadLine();
        int userGuess = inputString.ToInt32();
        Random rnd = new Random();
        double correctNumber = rnd.NextDouble() * MAX;
        correctNumber = Math.Round(correctNumber);
        Console.Write("The correct number was {0} and you guessed {1}...",
                       correctNumber, userGuess);
        if (userGuess == correctNumber) // They got it right!
        {
            Console.WriteLine("Congratulations!");
        }
        else // Wrong answer!
        {
            Console.WriteLine("Maybe next time!");
        }
    }
}