Table of Contents

    Understanding the if Statement in C#: Syntax and Usage Explained

    Understanding the if Statement in C#: Syntax and Usage Explained

    if Statement

    C# provides many decision making statements that help the flow of the C# program based on certain logical conditions. C# includes the following decision making statements.

    1. if statement
    2. if-else statement
    3. switch statement
    4. Ternary operator :?

    Here, you will learn about the if statements.

    Syntax:

    if(boolean expression)
    {
        // execute this code block if expression evalutes to true
    }

    The if statement contains boolean expression inside brackets followed by a single or multi line code block. At runtime, if a boolean expression is evalutes to true then the code block will be executed.

    Consider the following example where the if condition contains true as an expression.

    Example: if condition

    
    if(boolean expression)
    if(true)
    {
        Console.WriteLine("This will be displayed.");
    }
    
    if(false)
    {
        Console.WriteLine("This will not be displayed.");
    }
    

    As mentioned above, if statement can contain boolean expression. An expression which returns either true or false. Following example uses logical expression as a condition:

    Example: if condition

    
    int i = 10, j = 20;
    
    if (i > j)
    {
        Console.WriteLine("i is greater than j");
    }
    
    if (i < j)
    {
        Console.WriteLine("i is less than j");
    }        
    
    if (i == j)
    {
        Console.WriteLine("i is equal to j");
    }   
    

    Output

    
      i is less than j
    

    In the above example, the boolen expression i < j in the second 'if' statement evalutes to be true, only the second 'if' statement's code block will be executed. The first and third 'if' condition evalutes to false, so their code blocks will not be executed.