The if else clause - CSharp Language Basics

CSharp examples for Language Basics:if

Introduction

An if statement can optionally feature an else clause:

Demo Code

using System;//ww  w  .  j a v a  2s. com
class Test
{
   static void Main(){
      if (2 + 2 == 5)
         Console.WriteLine ("Does not compute");
      else
         Console.WriteLine ("False");        // False
   }
}   

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

Demo Code

using System;//from  w w w . j av a2  s  .c  o  m
class Test
{
    static void Main()
    {
        if (2 + 2 == 5)
            Console.WriteLine("Does not compute");
        else
          if (2 + 2 == 4)
            Console.WriteLine("Computes");    // Computes

    }
}

Changing the flow of execution with braces

Demo Code

using System;//from w ww. j  a va  2  s  .  c  o m
class Test
{
    static void Main()
    {
        if (true)
            if (false)
                Console.WriteLine();
            else
                Console.WriteLine("executes");

    }
}

This is semantically identical to:

if (true)
{
  if (false)
    Console.WriteLine();
  else
    Console.WriteLine ("executes");
}

We can change the execution flow by moving the braces:

if (true)
{
  if (false)
    Console.WriteLine();
}
else
  Console.WriteLine ("does not execute");

Related Tutorials