Parameters, variable scope and recursion
A method is more useful when it can adapt to what it receives. In this lesson you will see the different ways to pass information to a method: optional parameters, named arguments, out, ref and params. You will also learn a key idea: the scope of variables, that is, where each one exists. And we will close with recursion, the technique of a method that calls itself.
Default values and named arguments
A parameter can have a default value: if the caller does not pass it, that value is used. Optional parameters must go at the end of the list. When calling, you can give the name of the parameter followed by a colon, which improves readability and lets you skip optional parameters: Format("Ana", suffix: "!"). An important detail: numbers, bool and other simple types are passed by value, which means the method receives a copy and changing the parameter does not modify the caller's original variable.
Console.WriteLine(Format("Ana")); // Hello, Ana.
Console.WriteLine(Format("Ana", "Welcome")); // Welcome, Ana.
Console.WriteLine(Format("Ana", suffix: "!")); // Hello, Ana!
Console.WriteLine(Format(suffix: "?", name: "Luis")); // Hello, Luis?
int x = 10;
TryToChange(x);
Console.WriteLine(x); // 10: only a copy changed
string Format(string name, string greeting = "Hello", string suffix = ".")
{
return $"{greeting}, {name}{suffix}";
}
void TryToChange(int value)
{
value = 99;
}out, ref and params
The out modifier lets a method return extra values through parameters; you already know it from int.TryParse. The method is required to assign the out parameter before finishing. The ref modifier passes the variable itself, not a copy: the method can read and modify it, and the change is visible outside; the variable must have a value before the call. In both the declaration and the call you must write the word out or ref. Finally, params lets you receive a variable number of arguments as an array: Sum(1, 2, 3, 4). All three should be used sparingly; to return several values a tuple is usually clearer.
bool ok = TryDivide(10, 4, out double quotient);
Console.WriteLine($"{ok} {quotient}"); // True 2.5
int counter = 5;
Increment(ref counter);
Console.WriteLine(counter); // 6
Console.WriteLine(Sum()); // 0
Console.WriteLine(Sum(1, 2, 3, 4)); // 10
bool TryDivide(double a, double b, out double result)
{
if (b == 0)
{
result = 0; // must assign anyway
return false;
}
result = a / b;
return true;
}
void Increment(ref int value) => value++;
int Sum(params int[] numbers)
{
int total = 0;
foreach (int n in numbers) total += n;
return total;
}Variable scope
A variable exists only inside the block of braces where it was declared, and in the blocks nested inside it. When leaving the block, it disappears. This prevents different parts of the program from stepping on each other. A variable declared in a for cannot be used outside it, and the parameters and variables of a method only exist while the method runs. You cannot declare in an inner block a variable with the same name as a visible outer one. If you need the value afterwards, declare the variable before the block, at the level where you need it.
int total = 0; // visible in the whole file below
for (int i = 1; i <= 3; i++)
{
int square = i * i; // exists only inside this block
total += square;
}
// Console.WriteLine(i); // ERROR: i does not exist here
// Console.WriteLine(square); // ERROR: neither does square
Console.WriteLine(total); // 14
Console.WriteLine(Factorial(5)); // 120
Console.WriteLine(Fibonacci(10)); // 55
long Factorial(int n)
{
if (n <= 1) return 1; // base case
return n * Factorial(n - 1); // recursive case
}
int Fibonacci(int n) => n < 2 ? n : Fibonacci(n - 1) + Fibonacci(n - 2);Проверьте себя
Вопрос 1 из 2How is an int passed to a method by default?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов