← C# from Scratch
Lesson 24 of 39 · 10 XP
Method parameters
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
static void Hit(string who, int damage = 10) // damage is a parameter with a default value
{
Console.WriteLine($"{who} takes {damage}");
}
Hit("Orc"); // 10
Hit("Orc", 25);
Hit(damage: 5, who: "Goblin"); // named arguments — in any order
How arguments are passed. By default, as a copy of the value: changing int x inside isn't visible outside.
ref— pass the variable itself: the method can change it;out— the method must write a value (this is howint.TryParse(s, out int n)works);params int[] xs— any number of arguments:Sum(1, 2, 3).
static void Swap(ref int a, ref int b) { (a, b) = (b, a); }
int x = 1, y = 2;
Swap(ref x, ref y); // x = 2, y = 1
Arrays and objects are reference types: the method gets a reference and can change their contents even without ref.
Task. Finish the method MinMax(int[] a, out int min, out int max) and the method Sum(params int[] xs).
The program already reads the numbers and prints the results.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.