Chapter 4: Writing, Debugging, and Testing Functions [Flashcarder]
What is a fundamental principle of programming mentioned in the book?
Don’t Repeat Yourself (DRY).
What should you do if you find yourself writing the same statements over and over again while programming?
Turn those statements into a function.
How are functions described in the book?
Functions are like tiny programs that complete one small task, usually having inputs and outputs.
What feature was introduced with C# 9 and is used by the default project template for console apps since C# 10 and .NET 6?
The top-level program feature.
How do functions work with the automatically generated Program class and its <Main>$ method in top-level programs?
Functions defined in top-level programs become local functions within the <Main>$ method of the Program class.
What is the suggested practice for the placement of functions in a file?
Functions should be placed at the bottom of the file rather than mixed with other top-level statements.
What compiler error occurs if types like classes are declared in the middle of the Program.cs file?
Compiler error CS8803.
What does the compiler automatically generate for a local function in C#?
The compiler generates an inner method within the existing method or function, making it local to that context.
If the local function is within the Main
method of the Program
class, it remains nested inside that method, without creating a new class or method.
Where must import statements (using) be placed in the Program.cs file?
Import statements must go at the top of the Program.cs file.
Where can statements that go into the <Main>$ function be placed in the Program.cs file?
Statements that will go in the <Main>$ function can be mixed with functions in the middle of the Program.cs file. Any functions will become local functions in the <Main>$ method.
Why can’t local functions have XML comments?
Local functions cannot have XML comments because they cannot be used outside the member in which they are declared.
What is a better approach than defining functions within the Program.cs file?
A better approach is to write any functions in a separate file and define them as static members of the Program class.
What should you name a new class file for defining functions as static members of the Program class?
The name of the file does not actually matter, but using a naming convention like Program.Functions.cs is sensible.
What happens when you define a partial Program class with static functions in a separate file?
The compiler defines a Program class with a <Main>$ function and merges your function as a member of the Program class.
Why should you not define a namespace for your partial Program class?
If you define a namespace for your partial Program class, it will be in a different namespace and will not merge with the auto-generated partial Program class.
What is the strict definition of a parameter in a function?
A parameter is a variable in a function definition.
Provide an example of a function with a parameter.
void Hire(DateTime startDate) { // Function implementation. }
What is the strict definition of an argument in a function call?
An argument is the data you pass into the method’s parameters when a method is called.
Provide an example of passing an argument to a function.
DateTime when = new(year: 2024, month: 11, day: 5); Hire(when);
How can you specify the parameter name when passing an argument?
You can specify the parameter name by using named arguments.
For example, MyMethod(paramName: value);
DateTime when = new(year: 2024, month: 11, day: 5); Hire(startDate: when);
What terms do the official Microsoft documentation use interchangeably?
Named and optional arguments and
named and optional parameters.
How can a single object act as both a parameter and an argument?
Within a function implementation, a parameter can be passed as an argument to another function.
Provide an example where a parameter is passed as an argument to another function.
void Hire(DateTime startDate) { ... SaveToDatabase(startDate, employeeRecord); ... }
What is a classic example of naming a parameter in C#?
The parameter named args in the Main function.
static void Main(String[] args) { ... }
Summarize the difference between parameters and arguments.
Parameters define inputs to a function.
Arguments are passed to a function when calling the function.
What is a good practice when using the terms parameter and argument?
Try to use the correct term depending on the context, but do not get pedantic with other developers if they “misuse” a term.
What are cardinal numbers?
Cardinal numbers are numbers used to count, for example, 1, 2, and 3.
What are ordinal numbers?
Ordinal numbers are numbers used to order, for example, 1st, 2nd, and 3rd.
How is the factorial of a number calculated?
The factorial is calculated by multiplying the number by each of the positive integers less than it until reaching 1.
For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
What is the factorial of 0?
0! = 1
Provide the definition of a factorial for a positive integer n.
n! = n × (n − 1)!, for n ∈ { 1, 2, 3, … }
How is a negative number handled in the Factorial function?
The function throws an ArgumentOutOfRangeException.
What value does the Factorial function return when the input is 0?
The function returns 1.
Provide the implementation of the Factorial function.
static int Factorial(int number) { if (number < 0) { throw new ArgumentOutOfRangeException(message: $"The factorial function is defined for non-negative integers only. Input: {number}", paramName: nameof(number)); } else if (number == 0) { return 1; } else { return number * Factorial(number - 1); } }
What is recursion in the context of the Factorial function?
Recursion is a technique where a function calls itself within its implementation.
What are some potential problems with recursion mentioned in the text?
Recursion can lead to problems such as stack overflow due to too many function calls because memory is used to store data on every function call.
What is an alternative to recursion that is mentioned as more practical in C#?
Iteration is a more practical solution than recursion in C#.
Why do factorials of 13 and higher overflow the int type?
Factorials of 13 and higher overflow the int type because they exceed the maximum positive value that can be stored in a 32-bit integer, which is about 2 billion.
How can you modify the Factorial function to check for overflows?
Use the checked keyword in the statement that calls itself:
checked { return number * Factorial(number - 1); }
How can the RunFactorial function be modified to handle overflow and other exceptions?
static void RunFactorial() { for (int i = -2; i <= 15; i++) { try { WriteLine($"{i}! = {Factorial(i):N0}"); } catch (OverflowException) { WriteLine($"{i}! is too big for a 32-bit integer."); } catch (Exception ex) { WriteLine($"{i}! throws {ex.GetType()}: {ex.Message}"); } } }
What is the output of the modified RunFactorial function for numbers -2 to 15?
-2! throws System.ArgumentOutOfRangeException: The factorial function is defined for non-negative integers only. Input: -2 (Parameter 'number') -1! throws System.ArgumentOutOfRangeException: The factorial function is defined for non-negative integers only. Input: -1 (Parameter 'number') 0! = 1 1! = 1 2! = 2 ... 12! = 479,001,600 13! is too big for a 32-bit integer. 14! is too big for a 32-bit integer. 15! is too big for a 32-bit integer.
What is shown by default when calling a function in a code editor?
A tooltip with basic information is shown by default.
How can you improve the tooltip information in Visual Studio Code?
1.Customize Tooltip Settings:
* Adjust font size and color for better readability in Settings > Editor: Tooltip Font Size and Editor: Tooltip Color.
* Enable or disable specific tooltips by searching for tooltip in the settings (Ctrl+,) and customizing preferences.
2.Install Extensions:
Use IntelliSense extensions like IntelliSense for CSS class names in HTML, Path Intellisense, and language-specific extensions to enhance the detail and relevance of tooltip information.
3.Use Settings Sync:
* Sync your customized settings across different devices using Visual Studio Code’s Settings Sync feature.
4.Edit Settings JSON:
* Manually tweak tooltip settings in settings.json for more precise control.
What happens when you type 3 forward slashes (///) above a function in Visual Studio?
It expands into an XML comment template.
What is the primary purpose of XML documentation comments?
To be used with tools that convert the comments into documentation, like Sandcastle.
Why don’t local functions support XML comments?
Because local functions cannot be used outside the member in which they are declared, making it unnecessary to generate documentation for them.
What is the recommended practice for adding XML documentation comments?
Add XML documentation comments to all your functions except local functions.
What is F#?
F# is Microsoft’s strongly typed functional-first programming language that compiles to Intermediate Language (IL) to be executed by .NET.
What are some important attributes of functional languages?
1.Modularity: Breaks up a large complex code base into smaller pieces.
2.Immutability: Variables do not exist in the traditional sense, reducing bugs.
3.Maintainability: Code is cleaner and clearer (for mathematically-inclined programmers).
What are some features added to C# to support a more functional approach?
Tuples and pattern matching in C# 7.
Non-null reference types in C# 8.
Improved pattern matching and adding records in C# 9.
What is an expression-bodied function member in C#?
A concise syntax for defining methods and properties using the => character to indicate a return value.
What is the Fibonacci sequence?
A sequence of numbers starting with 0 and 1, where each subsequent number is the sum of the previous two numbers.
Provide the implementation of the FibImperative function.
static int FibImperative(uint term) { if (term == 0) { throw new ArgumentOutOfRangeException(); } else if (term == 1) { return 0; } else if (term == 2) { return 1; } else { return FibImperative(term - 1) + FibImperative(term - 2); } }
What does the FibImperative function do?
It calculates the Fibonacci sequence in an imperative style, using if-else statements and recursion.
Provide the implementation of the RunFibImperative function.
static void RunFibImperative() { for (uint i = 1; i <= 30; i++) { WriteLine("The {0} term of the Fibonacci sequence is {1:N0}.", arg0: CardinalToOrdinal(i), arg1: FibImperative(term: i)); } }
What is the output of the RunFibImperative function for the first 5 terms of the Fibonacci sequence?
The 1st term of the Fibonacci sequence is 0. The 2nd term of the Fibonacci sequence is 1. The 3rd term of the Fibonacci sequence is 1. The 4th term of the Fibonacci sequence is 2. The 5th term of the Fibonacci sequence is 3.
Provide the implementation of the FibFunctional function.
static int FibFunctional(uint term) => term switch { 0 => throw new ArgumentOutOfRangeException(), 1 => 0, 2 => 1, _ => FibFunctional(term - 1) + FibFunctional(term - 2) };
What does the FibFunctional function do?
It calculates the Fibonacci sequence in a declarative style using a switch expression and recursion.
Provide the implementation of the RunFibFunctional function.
static void RunFibFunctional() { for (uint i = 1; i <= 30; i++) { WriteLine("The {0} term of the Fibonacci sequence is {1:N0}.", arg0: CardinalToOrdinal(i), arg1: FibFunctional(term: i)); } }
What will be the result of running the RunFibFunctional function?
The result will be the same as the RunFibImperative function, displaying the first 30 terms of the Fibonacci sequence.
What is the main difference between FibImperative and FibFunctional functions?
FibImperative is written in an imperative style using if-else statements,
while FibFunctional is written in a declarative style using a switch expression.
What type of code editor must you use to debug problems at development time?
You must use a code editor that has debugging tools, such as Visual Studio 2022 or Visual Studio Code.
What is a breakpoint?
A breakpoint is a marker set on a line of code where the debugger will pause execution, allowing you to inspect the program state and find bugs.
How do you set a breakpoint in Visual Studio Code?
- Click on the line where you want to set the breakpoint.
- Navigate to Run | Toggle Breakpoint or press F9.
- A red circle will appear in the margin bar to indicate the breakpoint.
How do you start debugging in Visual Studio Code?
- Navigate to View | Run, or click the Run and Debug icon, or press Ctrl + Shift + D.
- Click the Run and Debug button at the top of the RUN AND DEBUG window.
- Select the Debugging project.
- Visual Studio Code will start the console app and pause at the breakpoint.
What is break mode in Visual Studio Code?
Break mode is when the debugger pauses execution at a breakpoint, highlighting the next line to be executed in yellow, and allowing inspection of the program state.
What are some common buttons in the debugging toolbar?
- Start/Continue/F5: Starts or continues running the project.
- Hot Reload: Reloads compiled code changes without restarting the app.
- Break All: Breaks into the next available line of code.
- Stop Debugging/Stop/Shift + F5: Stops the debugging session.
- Restart/Ctrl or Cmd + Shift + F5: Stops and restarts the program with the debugger attached.
- Show Next Statement: Moves the cursor to the next statement to be executed.
- Step Into/F11: Steps into the code statements.
- Step Over/F10: Steps over the code statements.
- Step Out/Shift + F11: Steps out of the current function.
- Show Threads in Source: Examines and works with threads in the application.
What are some of the most useful debugging windows in Visual Studio and Visual Studio Code?
- VARIABLES: Shows the name, value, and type of any local variables.
- WATCH: Shows the value of variables and expressions that you manually enter.
- CALL STACK: Shows the stack of function calls.
- BREAKPOINTS: Shows all your breakpoints and allows finer control over them.
- DEBUG CONSOLE or Immediate Window: Enables live interaction with your code.
How can you step into code using Visual Studio 2022 or Visual Studio Code?
Navigate to Run or Debug | Step Into, click on the Step Into button in the toolbar, or press F11.
What does the Step Over command do during debugging?
Step Over (F10) executes the next line of code, skipping over the method calls without stepping into them.