C# If Else
In real world, we always make different decisions based on different situations. Things happen the same in the programming world including C#.
Syntax:
if(Condition){ Code; }
- This is called If statement in C#.
- The condition is a boolean expression which is returned true or false.
- If the condition is true, the code or other statements will be run.
- If the condition is false, the code inside the curly bracket is skipped.
Example 01-25-01:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System; namespace TestIfStatement { class Program { static void Main(string[] args) { int mm = 88; if( mm >= 60 ){ Console.WriteLine("You passed the exam."); } Console.Read(); } } }
Output
You passed the exam.
- Line 10-11: Because mm = 88, mm >= 60 is returned true. Line 11 is executed and output the string.
- Line 10-12: We noticed there is only one statement in the curly brace. In this case, the curly brace can be omitted. So the if statement can be written in one line as follows.
if( mm >= 60 ) Console.WriteLine("You passed the exam.");
Syntax:
if(Condition){ Code 1; }else{ Code 2; }
- This is called If else statement in C#.
- The condition is a boolean expression which is returned true or false.
- If the condition is true, the code 1 will be executed.
- If the condition is false, the code 2 in the else statement will be executed.
Example 01-25-02:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System; namespace TestIfStatement { class Program { static void Main(string[] args) { int mm = 42; if( mm >= 60 ){ Console.WriteLine("You passed."); }else{ Console.WriteLine("You failed."); } Console.Read(); } } }
Output
You failed.
- Line 9: Set mm = 42.
- Line 10-14: mm >= 60 is returned false. So Line 13 is executed and output "You failed".
- Line 10-14: The curly braces can be omitted so the if statement can be written as follows.
if( mm >= 60 ) Console.WriteLine("You passed."); else Console.WriteLine("You failed.");
- If Else is a statement and ?: returned the value of an expression.
- In If-else statement, we can execute many statements but ?: expression can only return one value.
- If-else statement looks clearer than the ?: expression, especially in multiple if conditions.
- Sometimes, one can be changed to another.
The line 10-14 in the above example 01-25-02 can be changed to ?: expression as follows.
Console.WriteLine("You {0}.", mm >= 60 ? "passed":"failed");