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
Q

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

A

False

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

What is the result of the XOR 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
27
Q

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

A

False

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

What do conditional logical operators in C# do differently from their non-conditional counterparts?

A

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.

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

How does the ‘&&’ operator behave when the first operand is false?

A

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.

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

What is the purpose of the ‘||’ operator in conditional logical operations?

A

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.

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

What is demonstrated by using functions with conditional logical operators in C#?

A

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.

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

What is a good practice when using conditional logical operators with functions in C#?

A

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.

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

How can the ‘&’, ‘&&’, ‘|’, and ‘||’ operators differ when applied in a program?

A

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.

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

What are bitwise operators and what do they compare?

A

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.

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

What are binary shift operators used for in programming?

A

Binary shift operators are used to perform common arithmetic calculations much faster than traditional operators, such as multiplying by a factor of 2.

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

How do the AND, OR, and XOR bitwise operators function between two integers x = 10 and y = 6?

A

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).

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

What are the effects of the left-shift («) and right-shift (») operators on integers?
Illustrate with x = 10 and y = 6.

A

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 &laquo_space;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&raquo_space; 1) results in 3 (0011 in binary).

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

Explain the difference between bitwise and logical operators using the & and | symbols.

A

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.

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

What does the nameof operator return in C#?

A

The nameof operator returns the short name (without the namespace) of a variable, type, or member as a string value.

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

What is the purpose of the sizeof operator in C#, and does it require an unsafe code block?

A

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.

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

What operators are demonstrated in the expression:
char firstDigit = age.ToString()[0]; ?

A

Four operators are demonstrated:
= (assignment operator),
. (member access operator),
() (invocation operator), and
[] (indexer access operator).

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

How do if and switch selection statements differ in their application?

A

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.

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

What are the risks of omitting curly braces in if statements?

A

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.

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

What is pattern matching in C# 7, and how does it enhance safety in conditional statements?

A

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.

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

How can you use pattern matching with the if statement to check and cast types simultaneously?

A

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.

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

Demonstrate an example of pattern matching in a conditional check where an object needs to be identified as an integer.

A
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.

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

What is required at the end of every case section in a switch statement?

A

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.

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

How does a switch statement in C# compare values?

A

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.

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

What is the purpose of the ‘goto case’ keyword in a switch statement?

A

The ‘goto case’ keyword is used to jump to another case within the same switch statement.

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

When should the ‘goto’ keyword be used in a switch statement and what is the general opinion on using it?

A

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.

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

How does the Random.Shared.Next method work in C#?

A

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.

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

What happens if none of the case values match the switch expression?

A

The ‘default’ case executes if present.
If there is no matching case and no default, nothing in the switch executes.

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

Can you explain the use of labels in switch statements with an example?

A

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

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

What keyword is used in C# 7 and later to enhance the switch statement with pattern matching?

A

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.

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

How can a local variable be declared and assigned within a switch case statement for safe use in C# 7 and later?

A

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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What is the purpose of the when keyword in a switch case statement in C# 7 and later?

A

The when keyword is used for more specific pattern matching within a case statement, allowing conditions to be specified for the pattern.

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

Provide an example of using the when keyword in a switch case statement for pattern matching.

A

case Cat fourLeggedCat when fourLeggedCat.Legs == 4:
checks if an object of type Cat has exactly four legs.

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

How does pattern matching with the switch statement handle null values in the list of cases?

A

The switch statement can include a case null: to handle cases where the variable being checked is null.

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

What is the difference between the traditional and property pattern-matching syntax in C# 7 and later?

A

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.

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

How is the default case handled in a switch statement when pattern matching in C#?

A

The default case is evaluated last and typically handles any cases that do not match the earlier specific patterns.

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

What symbol is used in switch expressions to represent the default case, and what is its purpose?

A

The underscore (_) character is used as a discard in switch expressions to represent the default return value when none of the specified cases match.

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

How can switch expressions handle different subtypes and properties of a class in C#?

A

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).

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

What is the output behavior of switch expressions compared to traditional switch statements when applied in similar conditions?

A

The output of switch expressions is identical to that of switch statements, ensuring the same runtime behavior but with more concise and readable code.

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

What is an array in C# and how is it commonly indexed?

A

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.

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

How do you declare a single-dimensional array to store string values in C#?

A

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.

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

How do you initialize an array with a fixed size and assign values to it in C#?

A

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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

How do you iterate through the elements of an array in C#?

A

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}.");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

What is an alternative way to declare and initialize an array in C#?

A

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" };

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

Are arrays in C# always zero-indexed?

A

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.

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

How do you declare a two-dimensional array in C#?

A

A two-dimensional array in C# can be declared with the syntax: string[,] grid1; where [,] indicates it’s a two-dimensional array.

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

What is the syntax for initializing a two-dimensional array with predefined values in C#?

A

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"}
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

How can you discover the lower and upper bounds of a two-dimensional array in C#?

A

Use the GetLowerBound() and GetUpperBound() methods.
For example, grid1.GetLowerBound(0) returns the lower bound of the first dimension.

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

How do you iterate through all elements of a two-dimensional array in C#?

A

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]}");
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

How do you declare and allocate memory separately for a two-dimensional array in C#?

A

Declare the array and allocate memory as separate actions, e.g., string[,] grid2 = new string[3,4]; for declaration and memory allocation.

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

When declaring the size of a multi-dimensional array, what does the dimension size represent?

A

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).

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

What is a jagged array in C#?

A

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.

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

How do you declare and initialize a jagged array in C#?

A

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" }
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

How do you find the upper bound of a jagged array and its sub-arrays in C#?

A

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.

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

How do you iterate through all elements of a jagged array in C#?

A

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]}");
	}
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

What is a practical scenario for using jagged arrays in C#?

A

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.

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

What is list pattern matching in C#?

A

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
Q

Why is the order of patterns important when defining multiple list patterns in a switch expression?

A

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
Q

How do you match an empty array or collection using list pattern matching?

A

You use the pattern [] to match an empty array or collection.

84
Q

How do you match an array or collection with any number of items, including zero?

A

You use the pattern [..] to match an array or collection with any number of items, including zero.

85
Q

How do you match a list with any single item in C#?

A

Use the pattern [_] to match a list with any single item.

86
Q

How can you match a list with any single item and use the value in the return expression?

A

Use the pattern [var item1] to match a list with any single item and refer to the value as item1.

87
Q

How do you match exactly a list of two items with specific values in a specific order?

A

Use the pattern [7, 2] to match exactly a list of two items with the values 7 and 2 in that order.

88
Q

How do you match a list with exactly three items in C#?

A

Use the pattern [_, _, _] to match a list with exactly three items.

89
Q

How do you match a list with one or more items and refer to the first item in its return expression?

A

Use the pattern [var item1, ..] to match a list with one or more items and refer to the first item as item1.

90
Q

How do you match a list with two or more items and refer to the first and last items in its return expression?

A

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
Q

How do you match a list with one or more items and refer to the last item in its return expression?

A

Use the pattern [.., var lastItem] to match a list with one or more items and refer to the last item as lastItem.

92
Q

Provide a code example of list pattern matching to return descriptive text based on the pattern that matches best.

A
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
Q

What are inline arrays and why were they introduced in C# 12?

A

Inline arrays were introduced in C# 12 as an advanced feature to improve performance, primarily used by the .NET runtime team.

94
Q

Are inline arrays commonly used by C# developers?

A

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
Q

What is the declaration syntax for a one-dimensional array in C#?

A

datatype[].
For example, string[]

96
Q

How do you declare a three-dimensional array in C#?

A

string[,,]

97
Q

How do you declare a two-dimensional jagged array in C#?

A

string[][]

98
Q

How can you convert any sequence of items into an array in C#?

A

Using the ToArray extension method.

99
Q

When should you use an array instead of a collection?

A

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
Q

What is the difference between implicit and explicit casting in C#?

A

Implicit casting happens automatically and is safe,

while explicit casting must be performed manually as it may lose information.

101
Q

Provide an example of implicitly casting an int to a double in C#.

A
int a = 10;
double b = a; // Implicit cast from int to double
WriteLine($"a is {a}, b is {b}");
102
Q

Provide an example of explicitly casting a double to an int in C#.

A
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
Q

What must you be cautious of when casting between larger and smaller integer types?

A

Beware of potential data loss, such as losing precision or overflow issues when casting larger integers to smaller ones.

104
Q

What happens when you cast a long value that exceeds the range of an int in C#?

A
long e = 5_000_000_000;
int f = (int)e;
WriteLine($"e is {e}, f is {f}"); // Results in overflow
105
Q

How is negativity represented in binary numbers for signed integers?

A

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
Q

How is the maximum value for an int represented in binary?

A

The maximum value for an int (2147483647) is represented as 01111111111111111111111111111111 in binary.

107
Q

Provide the binary representation for the integers 8 to -8.

A

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
Q

How is the minimum value for an int represented in binary?

A

The minimum value for an int (-2147483648) is represented as 10000000000000000000000000000000 in binary.

109
Q

Why does the decimal value -1 have all ones in binary?

A

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
Q

What is the purpose of the System.Convert type in C#?

A

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
Q

How do you convert a double to an int using System.Convert?

A
double g = 9.8;
int h = System.Convert.ToInt32(g);
WriteLine($"g is {g}, h is {h}");
112
Q

What are the key differences between casting and converting in C#?

A

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
Q

What happens when you convert a double value of 9.8 to an int using System.Convert ?

A

When you convert a double value of 9.8 to an int using System.Convert, it rounds the value up to 10.

114
Q

What happens when you cast a long value that exceeds the range of an int ?

A

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
Q

What is the rounding rule taught in British primary schools for positive numbers?

A

Round up if the decimal part is .5 or higher, and
round down if the decimal part is less than .5.

116
Q

Which enum values does the .NET API use for rounding?

A

The .NET API uses the enum values:
AwayFromZero,
ToZero,
ToEven,
ToPositiveInfinity, and
ToNegativeInfinity.

117
Q

How does C# round positive numbers with a decimal part less than .5 and greater than .5?

A

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
Q

How does C# round numbers with a decimal part exactly at the midpoint .5?

A

C# rounds away from zero if the non-decimal part is odd and toward zero if the non-decimal part is even.

119
Q

Provide an example of rounding using System.Convert.ToInt32 with the value 9.5.

A
double value = 9.5;
int roundedValue = System.Convert.ToInt32(value); // roundedValue is 10
120
Q

What is Banker’s rounding?

A

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
Q

How does C# rounding differ from JavaScript rounding?

A

C# uses Banker’s rounding, which alternates rounding direction to reduce bias,
while JavaScript uses the primary school rule, always rounding .5 up.

122
Q

How do you declare and assign values to a two-dimensional array of doubles in C#?

A
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
Q

Provide the C# code to convert an array of double values to integers and output the results.

A
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
Q

How can you take control of rounding rules in C#?

A

You can take control of rounding rules in C# by using the Round method of the Math class with specified rounding options.

125
Q

How do you use Math.Round to round a number using the “away from zero” (British primary school) rule?

A

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
Q

Provide an example of rounding various numbers using Math.Round with MidpointRounding.AwayFromZero.

A
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
Q

What is the output when rounding the values 9.49, 9.5, and 9.51 using Math.Round with MidpointRounding.AwayFromZero ?

A

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
Q

What is a good practice to follow regarding rounding rules in programming languages?

A

For every programming language you use, check its rounding rules. They may not work the way you expect!

129
Q

What is the most common conversion in C# and why?

A

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
Q

What does the ToString method do in C#?

A

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
Q

Provide examples of converting different types to a string using ToString.

A
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
Q

Does the WriteLine method require explicit calls to ToString for outputting variables?

A

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
Q

Why might you explicitly call ToString when developing games with Unity?

A

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
Q

What is the output when converting an integer 12 to a string using ToString ?

A

The output is 12.

135
Q

What is the output when converting a boolean true to a string using ToString ?

A

The output is True.

136
Q

What is the output when converting a DateTime value to a string using ToString?

A

The output is the current date and time, for example, 08/28/2024 17:33:54.

137
Q

What is the output when converting an instance of System.Object to a string using ToString?

A

The output is System.Object.

138
Q

Why would you convert a binary object like an image or video to a string before storing or transmitting it?

A

Converting binary objects to a string of safe characters ensures that the bits are not misinterpreted by network protocols or different operating systems.

139
Q

What is the method called for converting binary objects to strings in a safe manner?

A

The method is called Base64 encoding.

140
Q

Which methods from the Convert class are used for Base64 encoding and decoding?

A

Convert.ToBase64String for encoding
and
Convert.FromBase64String for decoding.

141
Q

How do you create and populate a byte array with random values in C#?

A
byte[] binaryObject = new byte[128];
Random.Shared.NextBytes(binaryObject);
142
Q

How can you format the output of a byte array to display each byte in hexadecimal notation?

A

Use the format code :X2 to format the values, e.g.,

for (int index = 0; index < binaryObject.Length; index++)
{
    Write($"{binaryObject[index]:X2} ");
}
143
Q

Provide an example of converting a byte array to a Base64 string in C#.

A
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
Q

What is a sample output for a binary object represented as bytes in hexadecimal notation?

A

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
Q

What is a sample output for a binary object represented as a Base64 string?

A

Binary Object as Base64:
61OLEZ2D5k1FhfRo+BhV5bgzybb0ABB/
y1kjeyYYFjAAI+aPqRCwqebsVPtNM+FoUEbEHV+xV6Hb0GA00haTOT76CwgI6ZZdZM/
lzcVkM91IT+iwtBlRygNv9Bjj5ccMEceTvgM1RNFvqrAvqc7VA6gArCiPpRKLLr5AxDGopBo=

146
Q

What is the second most common conversion in C#?

A

The second most common conversion is from strings to numbers or date and time values.

147
Q

What is the opposite of the ToString method for converting strings to numbers or dates and times?

A

The opposite of the ToString method is the Parse method.

148
Q

Which types commonly have a Parse method in C#?

A

All number types and the DateTime type have a Parse method.

149
Q

Which namespace must be imported to work with cultures in C#?

A

The System.Globalization namespace must be imported.

150
Q

Provide an example of parsing an integer from a string in C#.

A
int friends = int.Parse("27");
WriteLine($"I have {friends} friends to invite to my party.");
151
Q

Provide an example of parsing a date and time value from a string in C#.

A
DateTime birthday = DateTime.Parse("4 June 1980");
WriteLine($"My birthday is {birthday}.");
152
Q

How do you set the current culture to ensure date parsing works correctly?

A

CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

153
Q

Provide the complete code example for parsing an integer and a date, then writing the results to the console.

A

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
Q

What is the default output format of a DateTime value in C#?

A

By default, a DateTime value outputs with the short date and time format.

155
Q

How can you format a DateTime to output only the date part using the long date format?

A

Use the format code:D, e.g.
WriteLine($"My birthday is {birthday:D}.");

156
Q

What is the sample output when running the code for parsing an integer and a date?

A

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
Q

What is the main problem with using the Parse method?

A

The main problem with using the Parse method is that it throws an exception if the string cannot be converted.

158
Q

What happens when you try to parse a string containing letters into an integer using int.Parse?

A

It throws a System.FormatException with the message “Input string was not in a correct format.”

159
Q

How does the TryParse method help avoid errors?

A

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
Q

What is the syntax for using the TryParse method with an integer?

A
if (int.TryParse(input, out int count))
{
    // Conversion succeeded, use count
}
else
{
    WriteLine("I could not parse the input.");
}
161
Q

Provide an example of using TryParse to parse user input.

A
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
Q

Can the System.Convert method be used to convert string values into other types, and what happens if it cannot convert?

A

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
Q

What is the standard signature for all methods following the Try naming convention in .NET?

A

The method must return a bool to indicate success or failure and use an out parameter in place of the return value.

164
Q

Provide an example of a Try method for parsing an integer.

A

bool success = int.TryParse("123", out int number);

165
Q

Provide an example of using a Try method for creating a Uri.

A

bool success = Uri.TryCreate("https://localhost:5000/api/customers", UriKind.Absolute, out Uri serviceUrl);

166
Q

What are exceptions in .NET used for?

A

Exceptions in .NET are used for failure reporting and are designed to indicate runtime errors.

167
Q

What happens when an exception is thrown in a .NET application?

A

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
Q

What is the default behavior of a console app when an unhandled exception occurs?

A

The console app outputs a message about the exception, including a stack trace, and then stops running, terminating the application.

169
Q

What is a good practice to avoid exceptions in .NET?

A

Avoid writing code that will throw an exception by performing checks using if statements when possible.

170
Q

When should you wrap code in a try block?

A

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
Q

Provide an example of a try-catch block for parsing an integer.

A
Write("What is your age? ");
string? input = ReadLine();
try
{
    int age = int.Parse(input);
    WriteLine($"You are {age} years old.");
}
catch
{
}
172
Q

What compiler warning might you see when parsing user input, and how can you address it?

A

You might see “Warning CS8604: Possible null reference argument.

Address it by using null checks or the null-forgiving operator (!).

173
Q

How do you use the null-forgiving operator to disable a compiler warning?

A

Add an exclamation mark (!) after the variable,
e.g., int age = int.Parse(input!);

174
Q

Why should you avoid using an empty catch statement in production code?

A

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
Q

What information does a stack trace provide when an exception is thrown?

A

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
Q

Why is it better to terminate the application rather than continue executing in a potentially corrupt state?

A

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
Q

How can you catch all types of exceptions in a catch block?

A

By declaring a variable of type System.Exception in the catch block:

catch (Exception ex)
{
    WriteLine($"{ex.GetType()} says {ex.Message}");
}
178
Q

How can you catch a specific type of exception, like FormatException?

A

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
Q

How can you catch an OverflowException and customize the error message?

A

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
Q

Why is the order of catch blocks important?

A

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
Q

What is a good practice when catching exceptions in C#?

A

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
Q

How can you add filters to a catch statement in C#?

A

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
Q

Provide an example of using a filter in a catch statement for a FormatException.

A
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
Q

What happens when an integer overflows in C# without any checks?

A

The integer overflows silently and wraps around to a large negative value.

185
Q

What is the output when incrementing an integer beyond its maximum value without checks?

A
Initial value: 2147483646
After incrementing: 2147483647
After incrementing: -2147483648
After incrementing: -2147483647
186
Q

What is the purpose of the checked statement in C#?

A

The checked statement tells .NET to throw an exception when an overflow happens instead of allowing it to happen silently.

187
Q

Provide an example of using the checked statement to catch an overflow.

A
checked
{
    int x = int.MaxValue - 1;
    x++;
    x++;
    x++;
}
188
Q

What is the output when incrementing an integer beyond its maximum value within a checked block?

A
Initial value: 2147483646
After incrementing: 2147483647
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
189
Q

How can you handle an overflow exception using try-catch?

A
try
{
    checked
    {
        int x = int.MaxValue - 1;
        x++;
        x++;
        x++;
    }
}
catch (OverflowException)
{
    WriteLine("The code overflowed but I caught the exception.");
}
190
Q

What is the purpose of the unchecked statement in C#?

A

The unchecked statement switches off overflow checks performed by the compiler within a block of code.

191
Q

Provide an example of a statement that causes a compile-time overflow error.

A

int y = int.MaxValue + 1;

192
Q

How do you disable compile-time overflow checks using unchecked ?

A
unchecked
{
    int y = int.MaxValue + 1;
    WriteLine($"Initial value: {y}");
    y--;
    WriteLine($"After decrementing: {y}");
    y--;
    WriteLine($"After decrementing: {y}");
}
193
Q

Exercise 3.1 – Test your knowledge

What happens when you divide an int variable by 0?

A

Throws a System.DivideByZeroException.

194
Q

Exercise 3.1 – Test your knowledge

What happens when you divide a double variable by 0?

A

Results in Infinity or -Infinity.

195
Q

Exercise 3.1 – Test your knowledge

What happens when you overflow an int variable, that is, set it to a value beyond its range?

A

Wraps around if not checked (e.g., int.MaxValue + 1 becomes int.MinValue);
throws OverflowException if checked.

196
Q

Exercise 3.1 – Test your knowledge

What is the difference between x = y++; and x = ++y;?

A

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
Q

Exercise 3.1 – Test your knowledge

What is the difference between break, continue, and return when used inside a loop statement?

A

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
Q

Exercise 3.1 – Test your knowledge

What are the 3 parts of a for statement and which of them are required?

A

Initialization, condition, and iteration.
None of them are required.

199
Q

Exercise 3.1 – Test your knowledge

What is the difference between the = and == operators?

A

= is the assignment operator.

== is the equality operator.

200
Q

Exercise 3.1 – Test your knowledge

Does the following statement compile?
for ( ; ; ) ;

A

Yes, it compiles and creates an infinite loop.

201
Q

Exercise 3.1 – Test your knowledge

What does the underscore _ represent in a switch expression?

A

Represents the default case (catch-all).

202
Q

Exercise 3.1 – Test your knowledge

What interface must an object “implement” to be enumerated over by using the foreach
statement?

A

IEnumerable or IEnumerable<T>.</T>