Sử dụng một câu lệnh if hoặc else if bên trong một câu lệnh if hoặc else if khác. Cú pháp cho câu lệnh if lồng nhau như sau -
if( boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
} Sau đây là một ví dụ cho thấy cách sử dụng các câu lệnh if lồng nhau trong C #. Ở đây, chúng ta có hai câu lệnh if kiểm tra hai điều kiện.
if (a == 5) {
/* if condition is true then check the following */
if (b == 10) {
/* if condition is true then print the following */
Console.WriteLine("Value of a is 5 and b is 10");
}
} Đây là ví dụ đầy đủ.
Ví dụ
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
//* local variable definition */
int a = 5;
int b = 10;
/* check the boolean condition */
if (a == 5) {
/* if condition is true then check the following */
if (b == 10) {
/* if condition is true then print the following */
Console.WriteLine("Value of a is 5 and b is 10");
}
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
} Đầu ra
Value of a is 5 and b is 10 Exact value of a is : 5 Exact value of b is : 10