C# if statement

Description

An if statement executes a body of code depending on whether a bool expression is true.

Syntax

You can selectively execute part of a program through the if statement. Its simplest form is shown here:


if(condition) {
   statement; 
}

condition is a Boolean (that is, true or false) expression. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed.

The complete form of the if statement is


if(condition) 
   statement; 
else 
   statement; 

The general form of the if using blocks of statements is


if(condition)/*w w  w.  j a  v  a  2 s  .  c o  m*/
{
    statement sequence 
}
else
{
    statement sequence 
}

if-else-if ladder. It looks like this:


if(condition)/*  w  w  w .  java2 s  .  co  m*/
   statement; 
else if(condition)
   statement; 
else if(condition)
   statement; 
.
.
.
else
   statement; 

Relational operators that can be used in a conditional expression.

Example 1

For example:


if (5 < 6) 
{ 
    Console.WriteLine ("true");       // True 
} 

If the body of code is a single statement, you can optionally omit the braces:


if (5 < 6) 
    Console.WriteLine ("true");       // True 

If more than one statement is to be executed as part of either condition, these statements need to be joined together into a block using curly braces ({.}).


bool isZero;  //from   ww w .  jav  a  2 s.co  m
if (i == 0)  
{ 
   isZero = true; 
   Console.WriteLine("i is Zero");  
}  
else  
{ 
   isZero = false; 
   Console.WriteLine("i is Non-zero");  
}

Example 2

You can combine else if clauses to test for multiple conditions:


using System; // w  w  w  .j  a  va  2s .  co  m

class MainEntryPoint 
{ 
   static void Main(string[] args) 
   {  
      string input="java2s.com";  
      if (input == "") 
      { 
         Console.WriteLine("You typed in an empty string."); 
      } 
      else if (input.Length < 5) 
      { 
         Console.WriteLine("The string had less than 5 characters."); 
      } 
      else if (input.Length < 10) 
      { 
         Console.WriteLine("The string had at least 5 but less than 10 Characters."); 
      } 
      Console.WriteLine("The string was " + input); 
   } 
} 

The code above generates the following result.

Example 3

You can nest if statements as follows:


using System;//from   w ww.  j a  v a 2 s  . c  o m

class Program
{
    static void Main(string[] args)
    {
        int i = 5;
        if (i > 0)
        {
            Console.WriteLine("more than 0");
            if (i > 3)
            {
                Console.WriteLine("more than 3");
            }
            else
            {
                Console.WriteLine("less than 3");

            }
        }
    }
}

The output:





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception