C# if-else Statement

Updated on     Kisan Patel

The if...else statement allows you to test whether or not a certain condition is fulfilled. If the condition is fulfilled, the program control is transferred to the blocks of code inside the if statement; otherwise, the control is skip the if block of code inside it statement.

The structure of if...else statement is:

if(condition) {
    //executes if condition become true
} else {
    //executes if condition become false
}

The else clause above is optional.

if(i == j) {
	Console.WriteLine("Greate! i is equal to j.");
}

In above example, the console message will be printed only if the expression i == j evaluates to true.

If i == j expression evaluates to false then you can use else clause as shown in below.

if(i == j) {
	Console.WriteLine("Greate! i is equal to j.");
} else {
	Console.WriteLine("Bad! i is not equal to j.");
}
using System;

namespace ConsoleApp
{
    class ConditionDemo
    {
        static void Main(string[] args)
        {
            int a, b, c;
            a = 10; b = 20; c = 30;

            if (a > b)
            {
                if (a > c)
                {
                    Console.WriteLine("a is largest number");
                }
                else
                {
                    Console.WriteLine("c is largest number");
                }
            }
            else
            {
                if (b > c)
                {
                    Console.WriteLine("b is largest number");
                }
                else
                {
                    Console.WriteLine("c is largest number");
                }
            }
        }
    }
}

The output of the above C# program…

c-sharp-if-else-demo


C#

Leave a Reply