C# 04 Study Notes Decision Statement

C#

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

 

4.2. Use bool Variable

📌equality operator

They are ==, !=.

OperatorMeaningExampleOutput(if age=42)
==Equal toage == 100false
!=Not Equal toage != 0true

 

📌relational operator

OperatorMeaningExampleOutput
<Less thanage < 21false
<=Less than or equal toage <= 18false
>Greater thanage > 16true
>=Greater than or equal toage >= 33true

 

📌conditional logic operator

&& , logic AND

||, logic OR.

 

📌Bad habit using logic operator🚨

Error:

This is hell wrong! When playing with logical operator, the variable can only appear once at a time.

😶 Not good but OK:

😄 Clear:

 

📌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.

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

 

📌good and bad examples

Error:

Since num is not boolean, it can't be placed into the ().

👍Recommend:

😶OK, but not recommend:

 

4.4. switch Statement

📌When should we use switch?

Use it when you have multiple and parallel conditions.

 

📌Rules Using switch

  • case must be unique.
  • every case should be ended with break

 

📌What is fall-through?

In short, it combines conditions with same behaviors.

 

Previous
Previous

Agile Software Development# 07 What is Agile Design?

Next
Next

C# 03 Study Notes Methods and Scope