C# Nested if Statements
In C#, nested if-else statements are valid, which means you can use another if or else if statement within an if or else if statement.
Syntax
The syntax for nested if statements in C#:
if(boolean_expression 1)
{
/* Executed when boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executed when boolean expression 2 is true */
}
}
You can nest else if...else in a similar way to nesting if statements.
Example
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
// Local variable definition
int a = 100;
int b = 200;
// Check the boolean condition
if (a == 100)
{
// Check the condition when the first condition is true
if (b == 200)
{
// Print the statement when the condition is true
Console.WriteLine("The value of a is 100 and the value of b is 200");
}
}
Console.WriteLine("Exact value of a is {0}", a);
Console.WriteLine("Exact value of b is {0}", b);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
The value of a is 100 and the value of b is 200
Exact value of a is 100
Exact value of b is 200