Chapter 3: Controlling Flow, Converting Types, and Handling Exceptions [Flashcarder]

1
Q

What topics are covered in this, 3rd, chapter?

A

The chapter covers writing code that performs operations on variables,
making decisions,
pattern matching,
repeating statements or blocks,
working with arrays,
type casting and converting,
exception handling, and checking for overflow.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are binary operators, and how do they work?

A

Binary operators work on two operands and return a new value that is the result of the operation.
For example, x + y and x * y are binary operators.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are unary operators, and how do they work?

A

Unary operators work on a single operand and can be applied before or after the operand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are examples of unary operators in C#?

A

Examples of unary operators include the increment operators (++x, x++), the typeof operator to get a type, the nameof operator to get a variable name, and the sizeof operator to get the size of a type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a ternary operator in C#?

A

A ternary operator works with three operands.
In C#, the conditional operator ?: is an example of a ternary operator.
It evaluates a Boolean expression and returns one of two values depending on whether the expression is true or false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why might experienced C# developers prefer using ternary operators over if statements?

A

Experienced C# developers might prefer ternary operators because they are concise and can result in cleaner code once you are familiar with reading them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference between the postfix ++ operator and the prefix ++ operator in C#?

A

The postfix ++ operator increments the value after it is used in an assignment.

The prefix ++ operator increments the value before it is used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

In the code snippet int a = 3; int b = a++;, what are the values of a and b after execution?

A

a will have a value of 4, and
b will have a value of 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

In the code snippet int c = 3; int d = ++c;, what are the values of c and d after execution?

A

Both c and d will have a value of 4.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the recommended practice for using the increment (++) and decrement (- -) operators in C# to avoid confusion?

A

The recommended practice is to avoid combining the use of increment (++) and decrement (- -) operators with the assignment operator (=).

Instead, perform these operations as separate statements to enhance code clarity and maintainability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What do binary arithmetic operators do in C# programming?

A

Binary arithmetic operators perform arithmetic operations on two numbers.
Common binary arithmetic operators includeL
addition (+),
subtraction (-),
multiplication (*),
division (/), and
modulus (%).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How does C# calculate the modulus (%) operation and what is the result for e % f when e is 11 and f is 3?

A

The modulus operation calculates the remainder after division of one number by another.

For e % f with e as 11 and f as 3, the result is 2, representing the remainder when 11 is divided by 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What difference does it make to the division operation in C# when the first operand is a floating-point number like g = 11.0?

A

When the first operand is a floating-point number, the division operation returns a floating-point result.

For instance, dividing g = 11.0 by f = 3 yields approximately 3.6666666666666665, reflecting the actual quotient without truncating to an integer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does the assignment operator += do in C#?

A

The += operator adds the right operand to the left operand and assigns the result to the left operand.

For example, p += 3 is equivalent to p = p + 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Explain the function of the -= operator in C#.

A

The -= operator subtracts the right operand from the left operand and assigns the result back to the left operand.

For instance, p -= 3 means p = p - 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Describe the use of *= in C#.

A

The *= operator multiplies the left operand by the right operand and assigns the result to the left operand.

p *= 3 translates to p = p * 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How does the /= operator work in C#?

A

The /= operator divides the left operand by the right operand and assigns the result to the left operand.

p /= 3 is equivalent to p = p / 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the purpose of the null-coalescing operator ?? in C#?

A

The ?? operator returns the left-hand operand if it is not null; otherwise, it returns the right-hand operand.

For example, int maxLength = authorName?.Length ?? 30 assigns maxLength the value of authorName.Length if authorName is not null, or 30 if authorName is null.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How does the null-coalescing assignment operator ??= function in C#?

A

The ??= operator assigns the right-hand value to the left-hand operand only if the left-hand operand is null.

For example, authorName ??= "unknown" assigns “unknown” to authorName if authorName is currently null.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the result of the AND logical operator when both operands are true?

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the result of the AND logical operator when one operand is true and the other is false?

A

False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the result of the OR logical operator when both operands are true?

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the result of the OR logical operator when one operand is true and the other is false?

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the result of the OR logical operator when both operands are false?

A

False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is the result of the **XOR** logical operator when **both operands are true**?
**False**
26
What is the result of the **XOR** logical operator when **one operand is true and the other is false**?
**True**
27
What is the result of the **XOR** logical operator when **both operands are false**?
**False**
28
What do **conditional logical operators** in C# do *differently* from their **non-conditional counterparts**?
**Conditional logical operators (&& and ||) perform *short-circuiting***, meaning they **do not evaluate the second operand if the first operand determines the result**, which can improve efficiency but may lead to skipped function calls if used with functions that have side effects.
29
How does the '**&&**' operator behave when the **first operand is false**?
The '&&' operator will **not evaluate the second operand if the first operand is false** because the overall expression cannot be true, thus ***short-circuiting*** the evaluation.
30
What is the purpose of the '**||**' operator in conditional logical operations?
The '||' operator will **not evaluate the second operand if the first operand is true** because the overall expression will be true regardless of the second operand, thereby short-circuiting further evaluation.
31
What is demonstrated by using **functions with conditional logical operators** in C#?
Using functions with conditional logical operators **shows how short-circuiting can prevent the function from executing** if the preceding condition already determines the result, potentially leading to efficiencies or missed **side effects** depending on the function's actions.
32
What is a good practice when using **conditional logical operators with functions** in C#?
It is good practice to **avoid using conditional logical operators with functions** that have side effects, as these functions may not execute if short-circuiting occurs, potentially leading to unexpected behavior or **bugs**.
33
How can the '**&**', '**&&**', '**|**', and '**||**' operators **differ** when applied in a program?
The **'&' and '|' operators evaluate both operands regardless of their values,** while the **'&&' and '||' operators may only evaluate the first operand if it is sufficient** to determine the result (true for '||', false for '&&'), demonstrating short-circuiting behavior.
34
What are **bitwise operators** and what do they compare?
Bitwise operators **compare the bits in the binary representation of a number**, where each bit (0 or 1) is compared individually to the bit in the same column.
35
What are **binary shift operators** used for in programming?
Binary shift operators are used to **perform common arithmetic calculations much faster than traditional operators,** such as multiplying by a factor of 2.
36
How do the **AND, OR,** and **XOR** bitwise operators function between two integers **x = 10 and y = 6**?
**AND (&)**: Compares each bit of x with y, and results in 1 if both bits are 1, otherwise 0. Example: **x & y results in 2 (00000010 in binary).** **OR (|)**: Compares each bit of x with y, and results in 1 if at least one of the bits is 1. Example: **x | y results in 14 (00001110 in binary).** **XOR (^)**: Compares each bit of x with y, and results in 1 only if the bits are different. Example: **x ^ y results in 12 (00001100 in binary).**
37
What are the effects of the **left-shift (<<) and right-shift (>>) operators on integers**? Illustrate with x = 10 and y = 6.
**Left-shift (<<):** The left-shift operator **shifts bits to the left, effectively multiplying the integer by 2 for each shift**. For example, shifting x = 10 (1010 in binary) by 3 bits (x << 3) results in **80** (01010000 in binary). **Right-shift (>>):** The right-shift operator **shifts bits to the right, effectively dividing the integer by 2 for each shift.** For example, shifting y = 6 (0110 in binary) by 1 bit (y >> 1) results in **3** (0011 in binary).
38
Explain the **difference between bitwise and logical operators** using the **&** and **|** symbols.
When operating **on integer values**, the **& and | symbols are bitwise operators**, comparing each corresponding bit of their operands. When used **with Boolean values** like true and false, they act as **logical operators**, determining the truth or falsehood through logical conjunction or disjunction, respectively.
39
What does the **nameof operator** return in C#?
The nameof operator **returns the short name** (without the namespace) of a *variable, type,* or *member* as a *string* value.
40
What is the **purpose of the sizeof** operator in C#, and does it require an *unsafe code* block?
The sizeof operator returns the **size in bytes of simple types**. It typically requires an **unsafe code block**, but for value types with a C# alias, like *int* and *double*, the sizes are hardcoded as constants by the compiler, so *no unsafe block is needed*.
41
What operators are demonstrated in the expression: `char firstDigit = age.ToString()[0];` ?
Four operators are demonstrated: **= (assignment operator)**, **. (member access operator)**, **() (invocation operator)**, and **[] (indexer access operator).**
42
How do ***if* and *switch* selection statements differ** in their application?
***If* statements** are used for **branching** based on Boolean expressions, potentially with multiple else if branches. ***Switch* statements** simplify code when a **single variable may have multiple values** that each require different processing.
43
What are the **risks of omitting curly braces in *if*** statements?
Omitting curly braces in if statements can introduce **serious bugs**, as demonstrated by the #gotofail bug in Apple's iOS, where an important SSL encryption check was accidentally skipped, compromising security.
44
What is **pattern matching** in C# 7, and how does it enhance safety in conditional statements?
Pattern matching in C# 7 allows for the use of the ***is*** **keyword** along with a **type check and local variable declaration directly in an if statement's condition**. This ensures that the variable used inside the block is safely of the specified type, enhancing **code safety** and **readability** by avoiding invalid operations on wrongly typed variables.
45
How can you use **pattern matching with the *if*** statement to **check and cast types** simultaneously?
You can use the ***is*** keyword **followed by a type and a new variable name**. For example, `if (o is int i)` checks if ***o*** is an ***int*** and assigns it to ***i*** if true. This allows ***i*** to be used within the scope of the if statement safely as an integer.
46
Demonstrate an **example of pattern matching in a conditional check** where an *object* needs to be identified as an *integer*.
```object o = "3"; // initially a string int j = 4; if (o is int i) { WriteLine($"{i} x {j} = {i * j}"); } else { WriteLine("o is not an int so it cannot multiply!"); }``` Change ***o*** to an **integer** to see multiplication in action, e.g., **o = 3**; then **i * j** will execute.
47
What is required at the **end of every case section** in a switch statement?
Each case section must **end with** a keyword such as: '**break**', '**goto case**', **have no statements**, '**goto a named label**', '**return**' to exit the function.
48
How does a ***switch*** statement in C# **compare values**?
A switch statement **compares a single expression against a list of multiple possible cases**, where each case represents a potential match to the expression's value.
49
What is the purpose of the **'goto case' keyword** in a switch statement?
The 'goto case' keyword is used to **jump to another case** within the same switch statement.
50
**When** should the '**goto**' keyword be used in a switch statement and what is the **general opinion** on using it?
The 'goto' keyword can jump to another case or a named label within a switch statement and should be used sparingly as it is **generally frowned upon by most programmers** due to potential complexity it adds to the code.
51
How does the ***Random.Shared.Next* method** work in C#?
It **generates a pseudo-random number within a specified range, where the lower bound is inclusive and the upper bound is exclusive**. Since .NET 6, the *Shared* instance of *Random* is **thread-safe** and can be used concurrently from any thread.
52
What happens if **none** of the **case values** match the **switch** expression?
The '**default' case executes if present**. If there is no matching case and no default, *nothing* in the switch executes.
53
Can you explain the use of **labels in switch statements** with an example?
In switch statements, labels like 'A_label' **can be targeted by 'goto' commands** from a case. For example, 'goto A_label;' will jump execution to the point marked by 'A_label:'.
54
What **keyword** is used in C# 7 and later to enhance the switch statement with **pattern matching**?
The **case keyword** can be used **with patterns**, not just literal values, to enhance the switch statement for pattern matching in C# 7 and later.
55
How can a **local variable** be declared and assigned within a **switch** case statement for *safe use* in C# 7 and later?
You can declare and assign a local variable **directly within a case statement** of a switch statement using pattern matching. This approach ensures that the **variable is safely scoped** and only accessible within the relevant case block. ```switch (obj) { case string s: Console.WriteLine($"String: {s}"); break;```
56
What is the purpose of the **when** keyword in a **switch** case statement in C# 7 and later?
The when keyword is used for **more specific pattern matching** within a case statement, allowing conditions to be specified for the pattern.
57
Provide an **example** of using the **when** keyword in a **switch** case statement for pattern matching.
`case Cat fourLeggedCat when fourLeggedCat.Legs == 4:` checks if an object of type Cat has exactly four legs.
58
How does **pattern matching** with the **switch** statement handle **null** values in the list of cases?
The switch statement **can include a case null:** to handle cases where the variable being checked is null.
59
What is the **difference** between the **traditional and property pattern-matching** syntax in C# 7 and later?
**Traditional Pattern Matching** (C# 7): - **Checks**: Type of an object. - **Usage**: Type-safe casting within `switch` and `is` expressions. - **Example**: ```if (obj is Person p) { Console.WriteLine($"Person: {p.Name}, Age: {p.Age}"); }``` **Property Pattern Matching** (C# 8+) - **Checks**: Type and properties of an object. - **Usage**: More detailed checks within `switch` and `is` expressions. - **Example**: ``` if (obj is Person { Age: >= 18 }) { Console.WriteLine("Found an adult person"); } ``` **Key Differences:** - **Traditional**: Focuses on type checks. - **Property**: Focuses on both type and property checks for more detailed matching.
60
How is the **default case** handled in a **switch** statement when **pattern matching** in C#?
The default case is **evaluated last** and typically handles any cases that do not match the earlier specific patterns.
61
What **symbol** is used in **switch** expressions to represent the **default** case, and what is its purpose?
The **underscore** (**_**) character is used as a **discard** in switch expressions to represent the **default** return value when none of the specified cases match.
62
How can **switch** expressions handle different **subtypes** and **properties of a class** in C#?
Switch expressions **can utilize pattern matching with conditions to return specific strings based on the subtype and attributes of objects**, such as different animal types in a class hierarchy (e.g., Cat and Spider with attributes like IsDomestic and IsPoisonous).
63
What is the **output** behavior of **switch expressions** compared to **traditional switch statements** when applied in similar conditions?
The **output** of switch expressions is **identical** to that of switch statements, ensuring the same runtime behavior but with more concise and readable code.
64
What is an **array** in C# and how is it commonly **indexed**?
An array in C# is a **data structure used to store multiple values of the same type.** The most common type of array in .NET is the **single-dimensional zero-indexed array**, which uses the normal **[ ] syntax**.
65
How do you **declare a single-dimensional array** to store string values in C#?
To declare a single-dimensional array of string values in C#, you can use the declaration **string[ ] names;**, where names can reference any size array of strings.
66
How do you **initialize an array** with a fixed size and assign values to it in C#?
You initialize an array in C# by **specifying its size and assigning values** to its indices, as follows: ```int[] numbers = new int[5]; // Initialize array with size 5 numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50;```
67
How do you **iterate through the elements of an array** in C#?
To iterate through an array in C#, use a ***for* or *foreach* loop**. For example: ```for (int i = 0; i < names.Length; i++) { WriteLine($"{names[i]} is at position {i}."); }```
68
What is an **alternative** way to **declare and initialize an array** in C#?
An alternative way to declare and initialize an array in C# is by using **array initializer syntax**. For example: `string[] names2 = { "Kate", "Jack", "Rebecca", "Tom" };`
69
Are arrays in C# always **zero-indexed**?
While the most common type of array in C#, the **szArray, is zero-indexed**, .NET also supports **multi-dimensional arrays (mdArray) which do not have to have a lower bound of zero**.
70
How do you **declare a two-dimensional array** in C#?
A two-dimensional array in C# can be declared with the syntax: `string[,] grid1;` where **[,]** indicates it's a two-dimensional array.
71
What is the syntax for **initializing a two-dimensional array** with predefined values in C#?
A two-dimensional array can be initialized with **predefined values** using the **syntax**: ```string[,] grid1 = { {"Alpha", "Beta", "Gamma", "Delta"}, {"Anne", "Ben", "Charlie", "Doug"}, {"Aardvark", "Bear", "Cat", "Dog"} };```
72
How can you discover the **lower and upper bounds of a two-dimensional array** in C#?
Use the ***GetLowerBound()*** and ***GetUpperBound()*** **methods**. For example, `grid1.GetLowerBound(0)` returns the lower bound of the first dimension.
73
How do you **iterate through all elements of a two-dimensional array** in C#?
Use **nested *for* loops** based on the array's bounds. For example: ```for (int row = 0; row <= grid1.GetUpperBound(0); row++) { for (int col = 0; col <= grid1.GetUpperBound(1); col++) { WriteLine($"Row {row}, Column {col}: {grid1[row, col]}"); } }```
74
How do you **declare and allocate memory separately for a two-dimensional array** in C#?
Declare the array and allocate memory as separate actions, e.g., `string[,] grid2 = new string[3,4];` for **declaration** and **memory** allocation.
75
When declaring the size of a multi-dimensional array, what does the **dimension size** represent?
The dimension size represents the **number of items each dimension can hold**. For `new string[3,4];`, the first dimension can hold **3 items** (**indices 0 to 2**), and the second dimension can hold **4 items** (**indices 0 to 3**).
76
What is a **jagged array** in C#?
A jagged array, also known as an "**array of arrays**," is a structure in C# where **each element is an array that can have different lengths**, allowing for a multi-dimensional array with **variable row sizes**.
77
How do you **declare and initialize a jagged array** in C#?
You declare and initialize a jagged array by **specifying each array within the main array.** Example: ```string[][] jagged = { new[] { "Alpha", "Beta", "Gamma" }, new[] { "Anne", "Ben", "Charlie", "Doug" }, new[] { "Aardvark", "Bear" } };```
78
How do you find the **upper bound of a jagged array** and its sub-arrays in C#?
Use the ***GetUpperBound(0)*** method on the jagged array to get the upper bound of the array of arrays, and apply the same method to each sub-array to find their respective upper bounds.
79
How do you **iterate through all elements of a jagged array** in C#?
Use **nested *for* loops**, accessing each sub-array and then each element within: ```for (int row = 0; row <= jagged.GetUpperBound(0); row++) { for (int col = 0; col <= jagged[row].GetUpperBound(0); col++) { WriteLine($"Row {row}, Column {col}: {jagged[row][col]}"); } }```
80
What is a **practical** scenario for using **jagged arrays** in C#?
Jagged arrays are ideal when dealing with **data structured in rows that vary in length**, such as data from different sources where each source may provide a different number of elements.
81
What is **list pattern matching** in C#?
List pattern matching, introduced in C# 11, works with **any type that has a public *Length* or *Count* property and has an indexer** using an *int* or *System.Index* parameter. It allows **patterns to be matched against arrays and collections**.
82
Why is the **order of patterns** important when defining **multiple list patterns** in a **switch** expression?
The order is important because the **more specific pattern must come first; otherwise, a more general pattern will match all cases**, making the specific pattern unreachable, causing a **compiler error**.
83
How do you **match an empty array or collection** using **list pattern matching**?
You use the **pattern []** to match an empty array or collection.
84
How do you **match an array or collection with any number of items, including zero**?
You use the **pattern [..]** to match an array or collection with any number of items, including zero.
85
How do you **match a list with any single item** in C#?
Use the pattern **[_]** to match a list with any single item.
86
How can you **match a list with any single item and use the value in the return expression**?
Use the **pattern [var item1]** to match a list with any single item and refer to the value as item1.
87
How do you **match exactly a list of two items with specific values in a specific order**?
Use the **pattern [7, 2]** to match exactly a list of two items with the values 7 and 2 in that order.
88
How do you **match a list with exactly three items** in C#?
Use the **pattern [_, _, _]** to match a list with exactly three items.
89
How do you **match a list with one or more items and refer to the first item in its return expression**?
Use the **pattern [var item1, ..]** to match a list with one or more items and refer to the first item as item1.
90
How do you **match a list with two or more items and refer to the first and last items in its return expression**?
Use the **pattern [var firstItem, .., var lastItem]** to match a list with two or more items and refer to the first item as firstItem and the last item as lastItem.
91
How do you **match a list with one or more items and refer to the last item in its return expression**?
Use the **pattern [.., var lastItem]** to match a list with one or more items and refer to the last item as lastItem.
92
Provide a code **example of list pattern matching** to return descriptive text based on the pattern that matches best.
```static string CheckSwitch(int[] values) => values switch { [] => "Empty array", [1, 2, _, 10] => "Contains 1, 2, any single number, 10.", [1, 2, .., 10] => "Contains 1, 2, any range including empty, 10.", [1, 2] => "Contains 1 then 2.", [int item1, int item2, int item3] => $"Contains {item1} then {item2} then {item3}.", [0, _] => "Starts with 0, then one other number.", [0, ..] => "Starts with 0, then any range of numbers.", [2, .. int[] others] => $"Starts with 2, then {others.Length} more numbers.", [..] => "Any items in any order.", };```
93
What are **inline arrays** and why were they introduced in C# 12?
Inline arrays were introduced in C# 12 as an **advanced feature to improve performance**, primarily used by the *.NET runtime team*.
94
Are **inline arrays** commonly used by C# developers?
Inline arrays are **less likely to be used by individual developers** unless they are public library authors, but developers will benefit from their use in libraries.
95
What is the **declaration syntax for a one-dimensional array** in C#?
**datatype[]**. For example, `string[]`
96
How do you **declare a three-dimensional array** in C#?
`string[,,]`
97
How do you **declare a two-dimensional jagged array** in C#?
`string[][]`
98
How can you **convert any sequence of items into an array** in C#?
Using the ***ToArray* extension method**.
99
When should you use an **array instead of a collection**?
Use an **array when you do not need to dynamically add and remove items**, as arrays are *more efficient* in **memory** use and improve **performance** by storing items contiguously.
100
What is the **difference between implicit and explicit casting** in C#?
**Implicit** casting happens **automatically** and is **safe**, while **explicit** casting must be performed **manually** as it may **lose** information.
101
Provide an **example of implicitly casting an *int* to a *double*** in C#.
```int a = 10; double b = a; // Implicit cast from int to double WriteLine($"a is {a}, b is {b}");```
102
Provide an **example of explicitly casting a *double* to an *int*** in C#.
```double c = 9.8; int d = (int)c; // Explicit cast from double to int WriteLine($"c is {c}, d is {d}"); // d loses the .8 part```
103
What must you be **cautious** of **when casting between larger and smaller integer types**?
Beware of **potential data loss**, such as **losing precision** or **overflow issues** when casting larger integers to smaller ones.
104
What happens when you **cast a *long* value that exceeds the range of an *int*** in C#?
```long e = 5_000_000_000; int f = (int)e; WriteLine($"e is {e}, f is {f}"); // Results in overflow```
105
How is **negativity represented in binary** numbers for signed integers?
In signed integers, the **first bit is used to represent negativity.** If the **bit** is **0**, the number is **positive**. If the **bit** is **1**, the number is **negative**.
106
How is the **maximum value for an *int* represented in binary**?
The maximum value for an *int* (**2147483647**) is represented as **01111111111111111111111111111111** in binary.
107
Provide the **binary representation for the integers 8 to -8**.
**8**: 00000000000000000000000000001000 **7**: 00000000000000000000000000000111 **6**: 00000000000000000000000000000110 **5**: 00000000000000000000000000000101 **4**: 00000000000000000000000000000100 **3**: 00000000000000000000000000000011 **2**: 00000000000000000000000000000010 **1**: 00000000000000000000000000000001 **0**: 00000000000000000000000000000000 **-1**: 11111111111111111111111111111111 **-2**: 11111111111111111111111111111110 **-3**: 11111111111111111111111111111101 **-4**: 11111111111111111111111111111100 **-5**: 11111111111111111111111111111011 **-6**: 11111111111111111111111111111010 **-7**: 11111111111111111111111111111001 **-8**: 11111111111111111111111111111000
108
How is the **minimum value for an *int* represented in binary**?
The minimum value for an *int* (**-2147483648**) is represented as **10000000000000000000000000000000** in binary.
109
Why does the ***decimal* value -1 have all ones** in binary?
The *decimal* value -1 is **represented by all ones** in binary (**11111111111111111111111111111111**). This occurs because of how negative numbers are represented in two's complement notation.
110
What is the **purpose of the *System.Convert* type** in C#?
The *System.Convert* type in C# is used to **convert between different data types, including all C# number types, Booleans, strings, and date and time values.**
111
How do you **convert a double to an int using *System.Convert***?
```double g = 9.8; int h = System.Convert.ToInt32(g); WriteLine($"g is {g}, h is {h}");```
112
What are the key **differences** between **casting and converting** in C#?
Key differences include: **Casting trims the part after the decimal point without rounding, while converting rounds the value**. **Converting throws an exception on overflow, while casting can allow overflows.**
113
What happens when you **convert a double value of 9.8 to an int using *System.Convert*** ?
When you convert a double value of 9.8 to an int using *System.Convert*, it **rounds the value up to 10**.
114
What happens when you **cast a *long* value that exceeds the range of an *int*** ?
When casting a long value that exceeds the range of an int, it can cause **overflow, resulting in unexpected values**. For example: ```long e = 5_000_000_000; int f = (int)e; WriteLine($"e is {e}, f is {f}"); // Results in overflow```
115
What is the **rounding rule** taught in British **primary schools** for positive numbers?
**Round *up* if the decimal part is .5 or higher**, and **round *down* if the decimal part is less than .5**.
116
Which ***enum* values** does the *.NET API* use for **rounding**?
The .NET API uses the enum values: ***AwayFromZero***, ***ToZero***, ***ToEven***, ***ToPositiveInfinity***, and ***ToNegativeInfinity***.
117
How does C# **round positive numbers with a decimal part less than .5 and greater than .5**?
C# **rounds *toward zero* if the decimal part is less than .5 and *away from zero* if the decimal part is more than .5**.
118
How does C# **round numbers with a decimal part exactly at the midpoint .5**?
C# **rounds away from zero if the non-decimal part is odd and toward zero if the non-decimal part is even.**
119
Provide an **example of rounding using *System.Convert.ToInt32*** with the value 9.5.
```double value = 9.5; int roundedValue = System.Convert.ToInt32(value); // roundedValue is 10```
120
What is **Banker's rounding**?
Banker's rounding is a **rounding rule that reduces bias by rounding *toward zero* if the decimal part is exactly .5 and the non-decimal part is even, and *away from zero* if the non-decimal part is odd**.
121
How does **C# rounding differ from JavaScript rounding**?
**C# uses Banker's rounding**, which alternates rounding direction to reduce bias, while **JavaScript uses the primary school rule**, always rounding .5 up.
122
How do you **declare and assign values to a two-dimensional array of doubles** in C#?
```double[,] doubles = { { 9.49, 9.5, 9.51 }, { 10.49, 10.5, 10.51 }, { 11.49, 11.5, 11.51 }, { 12.49, 12.5, 12.51 }, { -12.49, -12.5, -12.51 }, { -11.49, -11.5, -11.51 }, { -10.49, -10.5, -10.51 }, { -9.49, -9.5, -9.51 } };```
123
Provide the C# **code to convert an array of double values to integers and output the results**.
```WriteLine($"| double | ToInt32 | double | ToInt32 | double | ToInt32 |"); for (int x = 0; x < 8; x++) { for (int y = 0; y < 3; y++) { Write($"| {doubles[x, y],6} | {System.Convert.ToInt32(doubles[x, y]),7} "); } WriteLine("|"); } WriteLine();```
124
How can you take **control of rounding rules** in C#?
You can take control of rounding rules in C# by **using the *Round* method of the *Math* class** with specified rounding options.
125
How do you use ***Math.Round*** to round a number using the **"away from zero"** (British primary school) rule?
Use ***Math.Round*** with ***MidpointRounding.AwayFromZero*** as follows: ```double value = 9.5; double roundedValue = Math.Round(value, 0, MidpointRounding.AwayFromZero); WriteLine($"Math.Round({value}, 0, MidpointRounding.AwayFromZero) is {roundedValue}");```
126
Provide an **example of rounding various numbers using *Math.Round*** with *MidpointRounding.AwayFromZero*.
```double[] numbers = { 9.49, 9.5, 9.51, 10.49, 10.5, 10.51 }; foreach (double n in numbers) { WriteLine($"Math.Round({n}, 0, MidpointRounding.AwayFromZero) is {Math.Round(n, 0, MidpointRounding.AwayFromZero)}"); }```
127
What is the **output** when rounding the values *9.49, 9.5, and 9.51* using ***Math.Round* with *MidpointRounding.AwayFromZero*** ?
`Math.Round(9.49, 0, MidpointRounding.AwayFromZero)` is **9** `Math.Round(9.5, 0, MidpointRounding.AwayFromZero)` is **10** `Math.Round(9.51, 0, MidpointRounding.AwayFromZero)` is **10**
128
What is a **good practice** to follow regarding **rounding rules** in programming languages?
For every *programming language* you use, **check its rounding rules**. They may not work the way you expect!
129
What is the **most common conversion in C#** and why?
The most common conversion is **from any type to a string** for outputting as *human-readable text*. This is because **all types inherit a *ToString* method from the System.Object class**, which converts the current value of any variable into a textual representation.
130
What does the ***ToString* method** do in C#?
The *ToString* method **converts the current value of a variable into a textual representation.** For **types that *can't* be sensibly represented as text, it returns their namespace and type name** instead.
131
Provide **examples** of **converting** different types to a string using ***ToString***.
``` int number = 12; WriteLine(number.ToString()); // Outputs: 12 bool boolean = true; WriteLine(boolean.ToString()); // Outputs: True DateTime now = DateTime.Now; WriteLine(now.ToString()); // Outputs: current date and time object me = new(); WriteLine(me.ToString()); // Outputs: System.Object ```
132
Does the ***WriteLine* method** require **explicit** calls to ***ToString*** for outputting variables?
**No,** **passing any object to the WriteLine method implicitly converts it to a string.** Explicitly calling *ToString* is done here to emphasize the conversion process.
133
Why might you **explicitly call *ToString*** when developing games with **Unity**?
Explicitly calling ToString **avoids a boxing operation**, which can help **avoid memory garbage collection issues**, making it beneficial in performance-critical applications like game development with Unity.
134
What is the output when **converting an integer 12 to a string using *ToString*** ?
The output is **12**.
135
What is the output when **converting a boolean true to a string using *ToString*** ?
The output is **True**.
136
What is the **output when converting a *DateTime* value to a string using *ToString***?
The output is the **current date and time**, for example, *08/28/2024 17:33:54*.
137
What is the output when **converting an instance of *System.Object* to a string using *ToString***?
The output is ***System.Object***.
138
Why would you **convert a binary object like an image or video to a string** before storing or transmitting it?
Converting binary objects to a string of safe characters **ensures that the bits are not misinterpreted** by *network protocols* or different *operating systems*.
139
What is the **method** called for **converting binary objects to strings in a safe manner**?
The method is called ***Base64 encoding.***
140
Which **methods** from the ***Convert*** class are used for **Base64 encoding and decoding**?
***Convert.ToBase64String*** for **encoding** and ***Convert.FromBase64String*** for **decoding**.
141
How do you **create and populate a byte array with random values** in C#?
```byte[] binaryObject = new byte[128]; Random.Shared.NextBytes(binaryObject);```
142
How can you **format the output of a byte array** to display each byte in ***hexadecimal*** notation?
Use the format **code :X2** to format the values, e.g., ```for (int index = 0; index < binaryObject.Length; index++) { Write($"{binaryObject[index]:X2} "); }```
143
Provide an **example of converting a byte array to a *Base64* string** in C#.
```byte[] binaryObject = new byte[128]; Random.Shared.NextBytes(binaryObject); WriteLine("Binary Object as bytes:"); for (int index = 0; index < binaryObject.Length; index++) { Write($"{binaryObject[index]:X2} "); } WriteLine(); string encoded = Convert.ToBase64String(binaryObject); WriteLine($"Binary Object as Base64: {encoded}");```
144
What is a **sample output for a binary object represented as bytes** in *hexadecimal* notation?
EB 53 8B 11 9D 83 E6 4D 45 85 F4 68 F8 18 55 E5 B8 33 C9 B6 F4 00 10 7F CB 59 23 7B 26 18 16 30 00 23 E6 8F A9 10 B0 A9 E6 EC 54 FB 4D 33 E1 68 50 46 C4 1D 5F B1 57 A1 DB D0 60 34 D2 16 93 39 3E FA 0B 08 08 E9 96 5D 64 CF E5 CD C5 64 33 DD 48 4F E8 B0 B4 19 51 CA 03 6F F4 18 E3 E5 C7 0C 11 C7 93 BE 03 35 44 D1 6F AA B0 2F A9 CE D5 03 A8 00 AC 28 8F A5 12 8B 2E BE 40 C4 31 A8 A4 1A
145
What is a **sample output for a binary object represented as a *Base64*** string?
Binary Object as Base64: 61OLEZ2D5k1FhfRo+BhV5bgzybb0ABB/ y1kjeyYYFjAAI+aPqRCwqebsVPtNM+FoUEbEHV+xV6Hb0GA00haTOT76CwgI6ZZdZM/ lzcVkM91IT+iwtBlRygNv9Bjj5ccMEceTvgM1RNFvqrAvqc7VA6gArCiPpRKLLr5AxDGopBo=
146
What is the **second most common conversion** in C#?
The second most common conversion is **from strings to numbers or date and time** values.
147
What is the **opposite of the *ToString*** method for converting strings to numbers or dates and times?
The opposite of the *ToString* method is the ***Parse* method**.
148
Which **types** commonly have a ***Parse* method** in C#?
**All number types and the DateTime type** have a Parse method.
149
Which **namespace** must be imported to work with **cultures** in C#?
The ***System.Globalization*** namespace must be imported.
150
Provide an **example of parsing an integer from a string** in C#.
```int friends = int.Parse("27"); WriteLine($"I have {friends} friends to invite to my party.");```
151
Provide an **example of parsing a date and time value from a string** in C#.
```DateTime birthday = DateTime.Parse("4 June 1980"); WriteLine($"My birthday is {birthday}.");```
152
How do you set the **current culture** to ensure **date parsing** works correctly?
`CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");`
153
Provide the complete code **example for parsing an integer and a date**, then writing the results to the console.
`using System.Globalization; // To use CultureInfo.` ```// Set the current culture to make sure date parsing works. CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); int friends = int.Parse("27"); DateTime birthday = DateTime.Parse("4 June 1980"); WriteLine($"I have {friends} friends to invite to my party."); WriteLine($"My birthday is {birthday}."); WriteLine($"My birthday is {birthday:D}.");```
154
What is the **default output format of a DateTime** value in C#?
By default, a DateTime value outputs with the **short date and time format**.
155
How can you format a DateTime to **output only the date part** using the **long date format**?
Use the format **code:D**, e.g. `WriteLine($"My birthday is {birthday:D}.");`
156
What is the **sample** output when running the code for **parsing an integer and a date**?
I have 27 friends to invite to my party. My birthday is 6/4/1980 12:00:00 AM. My birthday is Wednesday, June 4, 1980.
157
What is the main **problem** with using the ***Parse* method**?
The main problem with using the Parse method is that it **throws an exception if the string cannot be converted.**
158
What happens when you try to **parse a string containing letters into an integer** using ***int.Parse***?
It **throws a *System.FormatException*** with the message "Input string was not in a correct format."
159
How does the ***TryParse*** method help **avoid errors**?
The *TryParse* method **attempts to convert the input string and returns *true* if it can convert it and *false* if it cannot**, avoiding exceptions.
160
What is the **syntax** for using the ***TryParse*** method with an integer?
```if (int.TryParse(input, out int count)) { // Conversion succeeded, use count } else { WriteLine("I could not parse the input."); }```
161
Provide an **example of using *TryParse*** to parse user input.
```Write("How many eggs are there? "); string? input = ReadLine(); if (int.TryParse(input, out int count)) { WriteLine($"There are {count} eggs."); } else { WriteLine("I could not parse the input."); }```
162
Can the ***System.Convert*** method be used to **convert string values into other types**, and what happens if it cannot convert?
**Yes**, the *System.Convert* method can be used to convert string values into other types, but it **throws an exception if it cannot convert.**
163
What is the **standard signature** for all methods following the ***Try*** naming convention in .NET?
The method must return a **bool** to indicate success or failure and use an ***out* parameter** in place of the **return** value.
164
Provide an **example of a *Try*** method for parsing an integer.
`bool success = int.TryParse("123", out int number);`
165
Provide an **example of using a Try** method for creating a ***Uri***.
`bool success = Uri.TryCreate("https://localhost:5000/api/customers", UriKind.Absolute, out Uri serviceUrl);`
166
What are **exceptions** in .NET used for?
Exceptions in .NET are used for **failure reporting** and are designed to indicate **runtime errors**.
167
What happens when an **exception is thrown** in a .NET application?
The *thread is suspended*, and if a **try-catch** statement **is defined**, the **catch block handles the exception**. **If not, the exception propagates up the call stack.**
168
What is the **default behavior** of a **console** app when an **unhandled exception** occurs?
The console app **outputs a message** about the **exception**, including a **stack trace**, and then **stops running**, terminating the application.
169
What is a **good practice to avoid exceptions** in .NET?
**Avoid writing code that will throw an exception** by performing **checks using *if* statements** when possible.
170
When should you **wrap code in a try block**?
Wrap code in a try block when you **know a statement can cause an error,** allowing the catch block to handle any exceptions thrown.
171
Provide an **example of a try-catch block** for parsing an integer.
```Write("What is your age? "); string? input = ReadLine(); try { int age = int.Parse(input); WriteLine($"You are {age} years old."); } catch { }```
172
What **compiler warning** might you see when **parsing user input**, and how can you address it?
You might see "**Warning CS8604: Possible null reference argument.**" Address it by using **null checks** or the **null-forgiving operator (!)**.
173
How do you use the **null-forgiving operator** to disable a compiler warning?
Add an **exclamation mark (!)** *after* the **variable**, e.g., `int age = int.Parse(input!);`
174
Why should you **avoid** using an **empty catch statement in production code**?
An empty catch statement **"swallows" exceptions and hides potential problems.** You should at least **log the exception** or **rethrow** it so that higher-level code can decide how to handle it.
175
What information does a **stack trace** provide when an **exception** is thrown?
A stack trace provides **information about the *call stack* at the point where the exception was thrown**, helping to diagnose the source of the error.
176
Why is it better to **terminate the application** rather than continue executing in a potentially **corrupt state**?
Continuing to execute in a potentially corrupt state can lead to more **serious errors** and **unpredictable behavior**, so it is **safer to terminate the application**.
177
How can you **catch all types of exceptions** in a catch block?
By **declaring a variable of type *System.Exception*** in the catch block: ```catch (Exception ex) { WriteLine($"{ex.GetType()} says {ex.Message}"); }```
178
How can you **catch a specific type of exception**, like *FormatException*?
By **adding a specific catch block** for the *FormatException* type: ```catch (FormatException) { WriteLine("The age you entered is not a valid number format."); } catch (Exception ex) { WriteLine($"{ex.GetType()} says {ex.Message}"); }```
179
How can you **catch an OverflowException** and **customize the error message**?
By **adding a catch block for the OverflowException type**: ```catch (OverflowException) { WriteLine("Your age is a valid number format but it is either too big or small."); } catch (FormatException) { WriteLine("The age you entered is not a valid number format."); } catch (Exception ex) { WriteLine($"{ex.GetType()} says {ex.Message}"); }```
180
Why is the **order of catch blocks** important?
The order of catch blocks is important because it relates to the **inheritance hierarchy of the exception types.** **More *specific* exceptions should be caught before more *general* ones**.
181
What is a **good practice** when **catching exceptions** in C#?
**Avoid over-catching exceptions.** They should often be allowed to propagate up the *call stack* to be handled at a level where more information is known about the circumstances that could change the logic of how they should be handled.
182
How can you add **filters** to a **catch statement** in C#?
You can add filters to a catch statement using the ***when* keyword**. ```catch (FormatException) when (amount.Contains("$")) { WriteLine("Amounts cannot use the dollar sign!"); }```
183
Provide an **example of using a filter** in a catch statement for a *FormatException*.
```try { decimal amountValue = decimal.Parse(amount); WriteLine($"Amount formatted as currency: {amountValue:C}"); } catch (FormatException) when (amount.Contains("$")) { WriteLine("Amounts cannot use the dollar sign!"); } catch (FormatException) { WriteLine("Amounts must only contain digits!"); }```
184
What happens when an **integer overflows** in C# **without any checks**?
The integer **overflows silently** and **wraps around to a large negative value.**
185
What is the **output** when **incrementing an integer beyond its maximum value without checks**?
```Initial value: 2147483646 After incrementing: 2147483647 After incrementing: -2147483648 After incrementing: -2147483647```
186
What is the purpose of the ***checked* statement** in C#?
The checked statement tells .NET to **throw an exception when an overflow happens** instead of allowing it to happen silently.
187
Provide an **example of using the *checked* statement** to catch an overflow.
```checked { int x = int.MaxValue - 1; x++; x++; x++; }```
188
What is the **output** when **incrementing an integer beyond its maximum value within a checked block**?
```Initial value: 2147483646 After incrementing: 2147483647 Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.```
189
How can you handle an **overflow exception using try-catch**?
```try { checked { int x = int.MaxValue - 1; x++; x++; x++; } } catch (OverflowException) { WriteLine("The code overflowed but I caught the exception."); }```
190
What is the purpose of the ***unchecked* statement** in C#?
The unchecked statement **switches off overflow checks performed by the compiler** within a block of code.
191
Provide an **example of a statement that causes a compile-time overflow error**.
`int y = int.MaxValue + 1;`
192
How do you **disable compile-time overflow checks** using ***unchecked*** ?
```unchecked { int y = int.MaxValue + 1; WriteLine($"Initial value: {y}"); y--; WriteLine($"After decrementing: {y}"); y--; WriteLine($"After decrementing: {y}"); }```
193
# Exercise 3.1 – Test your knowledge What happens when you **divide an int variable by 0**?
Throws a ***System.DivideByZeroException***.
194
# Exercise 3.1 – Test your knowledge What happens when you **divide a double variable by 0**?
**Results in *Infinity* or *-Infinity*.**
195
# Exercise 3.1 – Test your knowledge What happens when you **overflow an int variable, that is, set it to a value beyond its range**?
**Wraps around if not checked (e.g., int.MaxValue + 1 becomes int.MinValue); throws *OverflowException* if checked.**
196
# Exercise 3.1 – Test your knowledge What is the **difference** between **x = y++;** and **x = ++y;**?
**x = y++; assigns x the value of y before incrementing y.** **x = ++y; increments y first and then assigns x the new value of y.**
197
# Exercise 3.1 – Test your knowledge What is the **difference between *break*, *continue*, and *return*** when used **inside a loop** statement?
**break**: Exits the loop immediately. **continue**: Skips the current iteration and proceeds to the next iteration of the loop. **return**: Exits the method in which the loop is contained, terminating the loop and the method.
198
# Exercise 3.1 – Test your knowledge What are the **3 parts of a *for* statement** and which of them are *required*?
**Initialization**, **condition**, and **iteration**. *None of them are required.*
199
# Exercise 3.1 – Test your knowledge What is the **difference** between the **=** and **==** operators?
**=** **is the assignment operator.** **== is the equality operator.**
200
# Exercise 3.1 – Test your knowledge Does the following statement **compile**? `for ( ; ; ) ;`
**Yes**, it **compiles and creates an infinite loop.**
201
# Exercise 3.1 – Test your knowledge What does the **underscore _** represent in a **switch** expression?
Represents the **default case** (catch-all).
202
# Exercise 3.1 – Test your knowledge What **interface** must an **object** “implement” to be **enumerated** over by using the ***foreach*** statement?
IEnumerable or IEnumerable.