C# - if Statement



An if statement is a programming construct that lets us decide what to do based on the condition. It is a control flow statement that consists of a boolean expression that helps to execute different blocks of code depending on whether a condition is true or false.

Syntax

Following is the syntax of the if statement in C# −

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
}

If the boolean expression evaluates to true, then the block of code inside the if statement is executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) is executed.

Flow Diagram

C# if statement

Example: Using If Statement

Following is the basic example of the if statement, here display the statement based on the given condition −

using System;
namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;
        
         /* check the boolean condition using if statement */
         if (a < 20) {
            /* if condition is true then print the following */
            Console.WriteLine("a is less than 20");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

Output

When the above code is compiled and executed, it produces the following result −

a is less than 20;
value of a is : 10

Example: Filter Elements with Length of > = 5

In this example, we display the elements of characters with more than five elements using the if statement −

using System;
public class Example
{
   public static void Main(string[] args)
   {
      string[] arr = new string[] { "aman", "tutorialspoint", "India" };
      foreach (var item in arr)
      {
         // Use the if statement
         if (item.Length >= 5)
         {
            Console.WriteLine(item);
         }
      }
   }
}

Output

When the above code is compiled and executed, it produces the following result −

tutorialspoint
India
Advertisements