2.11 if else Statements

Stasoz
2 min readApr 23, 2022

--

You can check this course on my website.

Before you start reading, I want to ask you to like this article, so I will know that my work helps you ❤️

Conditional statements allow you to control the flow of program execution to not execute every line of code as it should be in the program.

For this in C# there are several statements, now we will consider if/else. if/else statements check the condition, which must return bool value and depending on the check, a particular code section is executed. Syntax:

if statement

After the if keyword must be specified condition that return bool value:

In the example above, if the number1 > number2 will return true, then condition will be met.

If our block contains one construction, we can write it as follows:

But if the block contains more than one construction, it is necessary to write with brackets {}:

We can also put more complex conditions in the check, but conditions must return bool value:

else if statement

What if we want to add another check, for example, if the number2 greater than the number1? Then we can use the else if statement:

Above the first check will return false because 10 is not greater than 15 and the program will jump to else if which return true (10 < 15).

Else if blocks can be created as many as you need, depending on your tasks, but once one of the conditions is met, the next checks will not be performed!

else statement

Well, what if no condition is met and we want to react on that somehow? For this you need else statement. It must be placed at the end, after if and else if statements and the code in it is executed if none of the above conditions worked:

Remember that example above can be written in short form:

Nested if/else/else if statements

It’s also good to know that all conditional statements can be nested:

Sometimes nested statements are useful and sometimes they complicate the code. Try not to overuse nested constructs and make the code as clear and short as possible.

Contents

Previous article -> 2.10 Operators Precedence and Associativity

Next article -> 2.12 Ternary operator

Join to our community in Telegram — https://t.me/itifico

If you want to support me, you can buy me a cup of coffee and I will drink it when I write the next article :)

Donations list:

  1. Dinesh Chintalapudi — 3$
  2. Unknown — 5$
  3. Neisy — 3$
  4. Unknown — 3$

--

--

Stasoz
Stasoz

Written by Stasoz

Full Stack Developer who is inspired by new technologies