If statement in C#
C Sharp

If statement in C#

Editorial Team
Editorial Team

Follow us on Discord or Telegram to get access to free tutorials and updates.

The If statement is one of the simplest and basic decision-making statement in c#. An if statement consists of a boolean expression (condition) followed by one or more statements. The statements will be executed only if the condition is found true.

Syntax

Following is he syntax of an if statement:

if(condition)
{
    //statement 1;
    //statement 2;
    //statement n;
}

Example

namespace LearnCSharp 
{
   class Program 
   {
      static void Main(string[] args) 
      {
         int num = 5;
         int num1 = 5;
         if (num >= 2) 
         {
            Console.WriteLine("num is greater than 2");
         }
         if(num == num1)
         {
            Console.WriteLine("num is equal to num1");
         }
      }
   }
}

The program will show the following result:

num is greater than 2
num is equal to num1

Nested if statement

An if statement can be specified in another if statement. This is known as nested if statement.

Example

namespace LearnCSharp 
{
   class Program 
   {
      static void Main(string[] args) 
      {
         int num = 5;
         int num1 = 5;
         if (num >= 2) 
         {
            Console.WriteLine("num is greater than 2");
            if(num == num1)
            {
               Console.WriteLine("num is equal to num1");
            }
         }
      }
   }
}

Use of if statement in C#

An if statement can be used in the program where you want to execute some statements only if a condition is satisfied.

Learn about other decision making statements in C#.