C# Teaching Materials: Comprehensive 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.
- **[Link]**: Uses placeholders (`{0}`, `{1}`) to format strings.
- **String Interpolation**: Embeds variables directly into a string using `$""`.
1.1 String Concatenation
String concatenation is the simplest way to combine strings. Use the `+` operator to join
literals and variables into a single string.
Example:
string name = "Alice";
int age = 30;
string message = "Hello, " + name + "! You are " + age + " years
old.";
[Link](message);
1.2 [Link]
The `[Link]` method allows you to use placeholders in a template string.
Placeholders (`{0}`, `{1}`, etc.) are replaced with corresponding variables.
Example:
string name = "Alice";
int age = 30;
string message = [Link]("Hello, {0}! You are {1} years
old.", name, age);
[Link](message);
1.3 String Interpolation
String interpolation is the most modern and readable way to format strings in C#. Variables
are embedded directly into the string using `$""`.
Example:
string name = "Alice";
int age = 30;
string message = $"Hello, {name}! You are {age} years old.";
[Link](message);
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:
- `var` infers the type from the value assigned.
- Operations like addition, multiplication, or concatenation respect the inferred type.
- Once inferred, the type cannot change; this is still statically typed, not dynamic.
Examples:
// Simple Type Inference
var name = "Alice"; // inferred as string
var age = 30; // inferred as int
var price = 9.99; // inferred as double
// Operations with Inferred Types
var incrementedAge = age + 1; // inferred as int
var totalPrice = price * 1.2; // inferred as double
[Link]($"Name: {name}, Age: {incrementedAge}, Total
Price: {totalPrice}");
Important: If you need to parse user input, you must convert it explicitly (e.g., using
`[Link]`).
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:
- Use `try-catch` to handle potential errors in a controlled way.
- Common exceptions include `FormatException` (invalid input) and
`DivideByZeroException` (division by zero).
- Use `finally` to run cleanup code, even if an exception occurs.
Examples:
try {
[Link]("Enter a number:");
int num = [Link]([Link]()); // May throw
FormatException
[Link]("Result: " + (10 / num)); // May throw
DivideByZeroException
} catch (FormatException) {
[Link]("Invalid input. Please enter a valid
number.");
} catch (DivideByZeroException) {
[Link]("Cannot divide by zero.");
} finally {
[Link]("End of program.");
}
Understanding [Link]
[Link] 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 [Link], which throws an exception for
invalid input.
How [Link] Works
It takes two arguments:
The input string to be converted.
An out parameter to store the converted value if successful.
If the conversion fails, the out parameter is set to 0 (default for int), and the method
returns false.
Example
[Link]("Enter a number:");
string input = [Link]();
if ([Link](input, out int number))
{
[Link]($"You entered: {number}");
}
else
{
[Link]("Invalid input. Please enter a valid
number.");
}
Explanation:
input: The string entered by the user.
number: The variable where the parsed value is stored if the conversion succeeds.
How It Handles Invalid Input:
If the user enters "abc", [Link] 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 [Link], 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:
- Each `case` checks a value of the variable.
- Use `break` to exit the `switch` after a case is executed.
- Include a `default` case to handle unmatched conditions.
Example:
[Link]("Enter a number (1-3):");
int choice = [Link]([Link]());
switch (choice) {
case 1:
[Link]("You selected Option 1.");
break;
case 2:
[Link]("You selected Option 2.");
break;
case 3:
[Link]("You selected Option 3.");
break;
default:
[Link]("Invalid option.");
break;
}
5. Logical Operators
Logical operators allow you to combine multiple conditions in an `if` statement. C# supports
three primary logical operators:
- `&&` (AND): True if both conditions are true.
- `||` (OR): True if at least one condition is true.
- `!` (NOT): Negates a condition.
Examples:
int age = 25;
if (age > 18 && age < 30) { // AND operator
[Link]("You are a young adult.");
}
if (age < 18 || age > 60) { // OR operator
[Link]("You qualify for special benefits.");
}
if (!(age > 18)) { // NOT operator
[Link]("You are underage.");
}
```