C# 04 Study Notes Decision Statement
4.Decision Statement
4.1. Declare bool
Variable
📌Romantic interpretation of Boolean
In the world of C# programming (unlike in the real world), everything is black or white, right or wrong, true or false.
📌true
, false
bool areYouReady;
areYouReady = true;
Console.WriteLine(areYouReady);
//output is true
4.2. Use bool
Variable
📌equality operator
They are ==
, !=
.
Operator | Meaning | Example | Output(if age=42) |
---|---|---|---|
== | Equal to | age == 100 | false |
!= | Not Equal to | age != 0 | true |
📌relational operator
Operator | Meaning | Example | Output |
---|---|---|---|
< | Less than | age < 21 | false |
<= | Less than or equal to | age <= 18 | false |
> | Greater than | age > 16 | true |
>= | Greater than or equal to | age >= 33 | true |
📌conditional logic operator
&&
, logic AND
||
, logic OR.
📌Bad habit using logic operator🚨
❌ Error:
xxxxxxxxxx
bool flag = num >= 0 && <= 100; //ERROR!!!
This is hell wrong! When playing with logical operator, the variable can only appear once at a time.
😶 Not good but OK:
xxxxxxxxxx
bool flag = num >= 0 && num <= 100;
😄 Clear:
xxxxxxxxxx
bool flag = (num>=0)&&(num<=100);
📌Short-circuiting⭐️
This is very useful for boosting the performance of the codes🚀:
Write the easier and computation-less condition on the LEFT side of the operator.
xxxxxxxxxx
int num = -10;
bool flag = (num>=0) && (num<=100);
xxxxxxxxxx
int num = -10;
bool flag = (num<=100) || (num>=0);
Apparently, putting the easier codes on the left is more efficient as they will jump out of the condition soon.
📌operator precedence and associativity⭐️
The operators higher up in the table take precedence over operators lower down:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/
4.3. if-else
Statement
📌sample of if
xxxxxxxxxx
if(flag)
{
//..
}
else if(flag2)
{
//..
}
else
{
//..
}
📌good and bad examples
❌Error:
xxxxxxxxxx
int num = 10;
if(num)
{
//..
}
Since num
is not boolean, it can't be placed into the ()
.
👍Recommend:
xxxxxxxxxx
bool flag = true;
if(flag)
{
//..
}
😶OK, but not recommend:
xxxxxxxxxx
bool flag = true;
if(flag==true)
{
//..
}
4.4. switch
Statement
📌When should we use switch
?
Use it when you have multiple and parallel conditions.
xxxxxxxxxx
int day = 5;
string dayName = "";
switch (day)
{
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
//..
default:
dayName = "Unknown";
break;
}
📌Rules Using switch
case
must be unique.- every
case
should be ended withbreak
📌What is fall-through?
xxxxxxxxxx
switch(flag)
{
case Hearts:
case Diamonds:
color="Red";
break;
case Clubs:
case:Spades:
color="Black";
break;
default:
color=null;
break;
}
In short, it combines conditions with same behaviors.