C# from Basics to Mastery — Part 2
Create a flow with conditional statements, loops, and methods
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
A program doesn't end with just storing values. You need to execute different code depending on conditions, repeat the same tasks, and divide methods into meaningful units.
Conditional statements and switches
string GetState(int health)
{
if (health <= 0)
{
return "Dead";
}
return health < 30 ? "Danger" : "Normal";
}
int reward = rank switch
{
"S" => 1000,
"A" => 500,
_ => 100
};
If is easier to read for simple two-prongs, and switch works well when comparing one value to multiple cases. _ is the remaining case that does not fit any of the preceding patterns.
loop
var damages = new[] { 10, 20, 15 };
int total = 0;
foreach (int damage in damages)
{
if (damage <= 0)
{
continue;
}
total += damage;
}
foreach is convenient for reading elements in order. If you need an index or need to directly control the repetition range, use for.
Adding or deleting elements of a collection within a loop can invalidate the enumeration. It is safer to collect the objects to be deleted separately or go through them from behind.
Methods and Early Returns
bool TryAttack(Player attacker, Monster target, out int damage)
{
damage = 0;
if (!attacker.IsAlive || !target.IsAlive)
{
return false;
}
damage = Math.Max(1, attacker.Attack - target.Defense);
target.TakeDamage(damage);
return true;
}
If you return input that cannot be processed first, the indentation of the normal flow will not deepen. The out parameter can be used to return both success or failure and the calculation result.
Method names should reveal the intent of the caller rather than the internal implementation. When conditions and iterations become long, it is better to ensure that each method has only one responsibility, rather than simply reducing the number of lines.