CSharp_Teaching_Notes
CSharp_Teaching_Notes
CSharp_Teaching_Notes
1. String Formatting
String formatting is a way to create dynamic strings by embedding variables and
expressions. In C#, you can format strings using three common methods:
- **String Concatenation**: Combines strings using the `+` operator.
- **String.Format**: Uses placeholders (`{0}`, `{1}`) to format strings.
- **String Interpolation**: Embeds variables directly into a string using `$""`.
Example:
1.2 String.Format
The `String.Format` method allows you to use placeholders in a template string.
Placeholders (`{0}`, `{1}`, etc.) are replaced with corresponding variables.
Example:
Example:
String interpolation is preferred because it is concise and avoids the need for placeholders
or operators.
2. var and Type Inference
`var` is a C# keyword that allows the compiler to automatically determine the type of a
variable based on the value assigned to it. This makes code simpler while maintaining type
safety.
Key Points:
Examples:
Important: If you need to parse user input, you must convert it explicitly (e.g., using
`int.Parse`).
3. Exception Handling
Exception handling is a way to manage runtime errors in your program, such as invalid
input or dividing by zero. In C#, this is done using `try-catch` blocks.
Key Points:
Examples:
try {
Console.WriteLine("Enter a number:");
int num = int.Parse(Console.ReadLine()); // May throw
FormatException
Console.WriteLine("Result: " + (10 / num)); // May throw
DivideByZeroException
} catch (FormatException) {
Console.WriteLine("Invalid input. Please enter a valid
number.");
} catch (DivideByZeroException) {
Console.WriteLine("Cannot divide by zero.");
} finally {
Console.WriteLine("End of program.");
}
Understanding int.TryParse
int.TryParse is a method used to safely convert a string into an integer without throwing an
exception if the conversion fails. Instead, it returns true if the conversion is successful or
false if it is not. This makes it a safer alternative to int.Parse, which throws an exception for
invalid input.
How int.TryParse Works
Example
Console.WriteLine("Enter a number:");
string input = Console.ReadLine();
Explanation:
input: The string entered by the user.
number: The variable where the parsed value is stored if the conversion succeeds.
If the user enters "abc", int.TryParse returns false, and the else block runs, displaying an
error message.
Key Points
Default Value Handling: If parsing fails, the out parameter is set to the default value (0 for
int).
No Exceptions: Unlike int.Parse, it does not throw exceptions, making it more robust for
user-facing applications.
4. Switch Statements
Switch statements are a clean way to handle multiple conditions based on a single variable.
They are often used as an alternative to multiple `if-else` statements.
Key Points:
Example:
Examples: