English
Summary
Conclusions
Methods divide a program into small, named parts that perform one task. A method declaration contains the return type, name, parameters, and body; in a program with top-level statements, methods are local functions, while overloaded methods are declared in a class. By default, arguments are passed by value: for reference types, the reference is copied. The ref, out, and in modifiers pass a variable by reference, optional parameters and named arguments simplify calls, and params allows a variable number of arguments. Overloading gives the same name to operations on different data types. A recursive method must have a base case; recursion depth is limited by stack size, and memoization eliminates repeated computations. XML comments document methods and appear in IntelliSense tooltips.
Self-check questions
- Why divide a program into methods? What makes a good method?
- What are the parts of a method declaration? What is a signature?
- How does a local function differ from a class method? What is the
staticmodifier for? - What happens when a value type or an array is passed by value?
- How do
ref,out, andindiffer? - How does the
TryParsepattern work? What doesout _mean? - What rules apply to declaring optional parameters? What are named arguments for?
- How does the
paramsmodifier work? Where must it appear? - What is method overloading? Is the return type part of the signature?
- How does the compiler choose an overload? When does ambiguity arise?
- How can a method return multiple values?
- What are a base case and a recursive step?
- What is the call stack? Why does stack overflow occur?
- What is memoization? Why is direct recursion for Fibonacci numbers slow?
- What are
///XML comments for?
Useful links
- Methods: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/methods
- Method parameters: https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/method-parameters
- Named and optional arguments: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments
- Local functions: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/local-functions
- XML comments: https://learn.microsoft.com/dotnet/csharp/language-reference/xmldoc/