0% found this document useful (0 votes)
11 views

CSharp_Teaching_Notes

This document provides comprehensive notes on C# string formatting methods, including string concatenation, String.Format, and string interpolation. It also covers the use of 'var' for type inference, exception handling with try-catch blocks, the int.TryParse method for safe integer conversion, switch statements for handling multiple conditions, and logical operators for combining conditions in if statements.

Uploaded by

Judith Nelson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

CSharp_Teaching_Notes

This document provides comprehensive notes on C# string formatting methods, including string concatenation, String.Format, and string interpolation. It also covers the use of 'var' for type inference, exception handling with try-catch blocks, the int.TryParse method for safe integer conversion, switch statements for handling multiple conditions, and logical operators for combining conditions in if statements.

Uploaded by

Judith Nelson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

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.
- **String.Format**: 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.";
Console.WriteLine(message);

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:

string name = "Alice";


int age = 30;
string message = String.Format("Hello, {0}! You are {1} years
old.", name, age);
Console.WriteLine(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.";
Console.WriteLine(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

Console.WriteLine($"Name: {name}, Age: {incrementedAge}, Total


Price: {totalPrice}");

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:

- 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 {
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

 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
Console.WriteLine("Enter a number:");
string input = Console.ReadLine();

if (int.TryParse(input, out int number))


{
Console.WriteLine($"You entered: {number}");
}
else
{
Console.WriteLine("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", 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:

- 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:

Console.WriteLine("Enter a number (1-3):");


int choice = int.Parse(Console.ReadLine());
switch (choice) {
case 1:
Console.WriteLine("You selected Option 1.");
break;
case 2:
Console.WriteLine("You selected Option 2.");
break;
case 3:
Console.WriteLine("You selected Option 3.");
break;
default:
Console.WriteLine("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
Console.WriteLine("You are a young adult.");
}
if (age < 18 || age > 60) { // OR operator
Console.WriteLine("You qualify for special benefits.");
}
if (!(age > 18)) { // NOT operator
Console.WriteLine("You are underage.");
}
```

You might also like