If-else statement in C#
C Sharp

If-else statement in C#

Mishel Shaji
Mishel Shaji

In an if-else statement, the if statement is followed by an else block. If the condition specified in the if statement failed, statements in the else block will be executed.

Syntax

if(codition)
{
    //Execute this
}
else
{
    //Execute this
}

Example

using System;
class LearnCSharp
{
	static void main()
	{
		a = 5;
		b = 10;
		if (a > b)
		{
		        Console.WriteLine("a is greater than b");
		}
		else
		{
			Console.WriteLine("a is less than b");
		}
                Console.ReadLine();
	}
}

The above program, when executed will produce the following output:

a is less than b

Else-if statement

An if-else-if statement is used when we want to check several conditions using the if-else statement. Please keep in mind that if an expression specified in any one of the else-if statement is found true, the rest of the statements will not be executed.

Syntax

if(condition)
{
   //Execute this
} 
else if(condition)
{
   //Execute this
} 
else if( boolean_expression 3)
{
   //Execute this
}
else 
{
   //Execute this
}

Example

using System;
namespace LearnCSharp
{
   class Program
   {
      static void Main(string[] args) 
      {
         int a = 1;
         if (a == 5) 
         {
            Console.WriteLine("I am in if statement");
         } 
         else if (a <= 3) 
         {
            Console.WriteLine("a is less than 3");
         } 
         else if (a == 1) 
         {
            Console.WriteLine("a is equal to 1");
         } 
         else 
         {
            Console.WriteLine("End of the statements");
         }
         Console.ReadLine();
      }
   }
}

Output

a is less than 3

Note that a is equal to 1 is not printed. It is because a condition prior to that statement is executed.