C# If Statement

Control Structures in C#: The Control Structures help us to control the flow of the application code execution. These C# flow control structures categorized into two types—they are Branching and looping.

C# If Statement Example

Branching

Branching is useful for decision making by selecting one option from multiple options.

In case if we want to decide on multiple options, we opt for branching statements like if, if else, etc.

For example, if we want to check whether a number is odd or even. Then we have to decide based on two options, i.e., whether that number is divisible by two or not.

Simple C# If Statement

The simple if statement in C# is useful to execute code, only if the condition specified in the if statement is true. The syntax of the C# if statement is as shown below

If<condition>
{
   Statements; //These statements are executed if condition is true
}

C# If Statement Example

In this C# if statement example, we write code for the following requirement.

Read numbers 1 to 4 and print in words. If the number is not in between 1 to 4, then print as an invalid number.

using System;
class Program
{
    static void Main()
    {
       int i =  int.Parse(Console.ReadLine());


        if (i == 1)
        {
            Console.WriteLine("input number is one");
        }
        if (i == 2)
        {
            Console.WriteLine("input number is two");
        }
        if (i == 3)
        {
            Console.WriteLine("input number is three");
        }
        if (i == 4)
        {
            Console.WriteLine("input number is four");
        }
        if (i != 1 && I != 2 && I != 3 && I != 4)
        {
            Console.WriteLine("input number is invalid");
        }
    }
}

OUTPUT

C# If Statement Example 1

ANALYSIS

In the above code, using the C# if statements, we compared the input number with the numbers 1 to 4.

Here we have taken an integer variable i to store the input number. Since Console.ReadLine() returns a string, and we explicitly converted to an integer using Parse.int

The input number is given as 3

The C# compiler started checking number 3 with 1, 2, 3,4, and hence it is 3, it has given output as follows. 

input number is three

NOTE: The compiler checks every if condition in the code, and it won’t exist even after the condition is satisfied in the middle of the code itself, i.e., i==3 in the above example code.