Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
if-else Chain | Control Structures
course content

Зміст курсу

C# Basics

if-else Chainif-else Chain

We can add additional conditions using the else if keyword. The additional conditions are evaluated in case the previous conditions are not met.

For example:

cs

main.cs

In the above program we chained conditions using if-else if. This is called Conditional Chaining. The first condition value_1 < value_2 is evaluated. Since it is false, the program skips to the next condition value_1 > value_2 which is true and hence it executes its code block and stops executing the chain further.

The main feature of Conditional Chaining is that it stops executing the chain as soon as a condition is met.

Consider the following code:

cs

main.cs

Even though all three conditions are true, it stops executing on the first condition since it's a chain.

Now let's try writing it using simple if keywords without chaining:

cs

main.cs

In the above case, each condition is evaluated individually and not treated as a part of any chain hence all three statements are outputted.

We can also add the else keyword at the end of the if-else chain which will execute if no condition is matched:

cs

main.cs

Which lines will be included in the output of the following program?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 3. Розділ 9
course content

Зміст курсу

C# Basics

if-else Chainif-else Chain

We can add additional conditions using the else if keyword. The additional conditions are evaluated in case the previous conditions are not met.

For example:

cs

main.cs

In the above program we chained conditions using if-else if. This is called Conditional Chaining. The first condition value_1 < value_2 is evaluated. Since it is false, the program skips to the next condition value_1 > value_2 which is true and hence it executes its code block and stops executing the chain further.

The main feature of Conditional Chaining is that it stops executing the chain as soon as a condition is met.

Consider the following code:

cs

main.cs

Even though all three conditions are true, it stops executing on the first condition since it's a chain.

Now let's try writing it using simple if keywords without chaining:

cs

main.cs

In the above case, each condition is evaluated individually and not treated as a part of any chain hence all three statements are outputted.

We can also add the else keyword at the end of the if-else chain which will execute if no condition is matched:

cs

main.cs

Which lines will be included in the output of the following program?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 3. Розділ 9
some-alt