CSharp - Statement if statement

Introduction

An if statement executes a statement if a bool expression is true. For example:

if ( 1 < 2 )
    Console.WriteLine ("true");       // true

The statement can be a code block:

if ( 1 < 2 )
{
       Console.WriteLine ("true");
       Console.WriteLine ("Let's move on!");
}

else clause

An if statement can optionally have an else clause:

if (2 + 2 == 5)
       Console.WriteLine ("Does not compute");
else
       Console.WriteLine ("False");        // False

Within an else clause, you can nest another if statement:


if (2 + 2 == 5)
       Console.WriteLine ("Does not compute");
else
       if (2 + 2 == 4)
            Console.WriteLine ("Computes");    // Computes

Demo

using System;
class MainClass//from   w  w w  .  j a va2s.co  m
{
   public static void Main(string[] args)
   {

        if (2 + 2 == 5)
               Console.WriteLine ("Does not compute");
        else
               if (2 + 2 == 4)
                    Console.WriteLine ("Computes");    // Computes
    

   }
}

Result

Quiz

Exercise