C# If Statements

In C#, If Statements are used to check the condition. Expression given in if statement is evaluated, If it is true then if block gets executed if it is false then else block gets executed. There are four types of if statements:

  1. If Statements
  2. If Else Statements
  3. Nested If Statement
  4. If else if ladder
If Statement: In C#, If statement checks the condition and executes If block on the true condition.

Syntax:
if(<Condition>)
{
//statements
}
C# If statement Example :
using System;
public class IfExample1
{
public static void Main (string[] args)
{
Console.WriteLine("Enter Your Age??");
int age=Convert.ToInt32(Console.ReadLine()); //reading data from console
if(age>=18)  //checking for age less the 18
{
Console.WriteLine("YES, YOU ARE ELIGIBLE FOR VOTE ");
}
if(age<18)
{
Console.WriteLine("NO, YOU CAN’T VOTE, YOU SHOULD WAIT FOR SOMETIME");
}
}
}
Output
Enter your age ?
12
No, YOU CAN’T VOTE, YOU SHOULD WAIT FOR SOMETIME
19
YES, YOU ARE ELIGIBLE FOR VOTE
  1. if else statement:
if the condition provided in if statement is true then if block gets executed and if it fails then else block gets executed.

Syntax:
if(<Condition>
{
//Statements will be executed if condition passes
}
else
{
//other statements will be executed if condition fails
}
C# If else Statement Example
using System;
public class IfElseExample
{
public static void Main (string[] args)
{
int num=Convert.ToInt32(Console.ReadLine());
if(num%2==0) //whether number is completely divisible  by 2 
{
Console.WriteLine("the number is even");
}
else
{
Console.WriteLine("The number is odd");
}
}
}
Output
2
The number is even
5
The number is od
  1. Nested If statement:
if(<condition>) { if(<condition>) { //statements } if(<Condition>) { //some statements } } else { if(<Condition>) { //statements } else(<Condition>) { //Statements } } 

  1. if else if ladder statements:
if else if provides various options in operations. It checks multiple condition on an operand and provides the result.

Syntax:
if(<Condition>)
{
//if the condition is true then this block will be executed
}
else if(<Condition>)
{
//if the if condition fails and this passes then this block will be executed
}
else if(<Condition>)
{
//Some other statements
}
else
{
//some statements
}
C# If Else If ladder Statement:
using System;
public class IfElseExample
{
public static void Main (string[] args)
{
int num=Convert.ToInt32(Console.ReadLine());
if(num%2==0) //whether number is completely divisible  by 2 
{
Console.WriteLine("the number is even");
}
else
{
Console.WriteLine("The number is odd");
}
}
}
Output:
2
The number is even
5
The number is odd