Programming is as much about making decisions as it is about defining behavior. [Chapter 3 of C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals ](https://www.amazon.com/13-NET-Cross-Platform-Development-Fundamentals/dp/183588122X)explores three foundational skills: controlling program flow, converting types safely, and handling exceptions. These are essential tools for writing reliable and adaptable software.
Conditional Logic with if and switch
At the heart of decision-making are conditional statements:
If statements evaluate conditions and execute code only if they’re true:
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}switch expressions, a modern feature of C#, provide a cleaner way to handle multiple cases:
string category = age switch
{
< 13 => "Child",
< 18 => "Teenager",
_ => "Adult"
};
Console.WriteLine(category);
This expressive syntax makes your code both concise and readable.
Iteration with Loops
Repetition is handled through loops, which simplify tasks such as processing collections or performing repeated calculations. The chapter explains the most common ones:
- for loops when the number of iterations is known.
- while loops when conditions drive repetition.
- foreach loops for stepping through arrays and collections
Example:
foreach (char c in "CSharp")
{
Console.WriteLine(c);
}
This outputs each character one by one, demonstrating how easily you can traverse data.
Converting Between Types
C# is strongly typed, but real-world data often requires conversion. Chapter 3 introduces:
- Implicit conversions: automatic when no data is lost (e.g., int to double).
- Explicit casts: needed when narrowing types (e.g., double to int).
- Helper classes like Convert.ToInt32() or int.Parse() for safe transformations.
For example:
string input = "42";
int result = Convert.ToInt32(input);
Type conversion is a key skill for avoiding unexpected runtime errors.
Exception Handling
Even well-written code can fail due to unforeseen situations like missing files or invalid input. This is where exceptions come in.
The pattern looks like this:
try
{
int number = int.Parse("not a number");
}
catch (FormatException ex)
{
Console.WriteLine($"Input error: {ex.Message}");
}
finally
{
Console.WriteLine("Operation completed.");
}
- try encloses code that might fail.
- catch defines how to react if it does.
- finally executes cleanup code, no matter what.
This structured approach helps build robust and fault-tolerant applications.
By combining control flow, type conversions, and exception handling, developers gain the tools to write programs that are both logical and resilient. These concepts may seem basic, but they form the bedrock of every scalable system.
📘 Explore these concepts in more detail in C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals by Mark J. Price.
Top comments (0)