C#
Summary - Method parameters
Combine default, params, ref and out to write a calculation method.
Summary - Method parameters
In this section you learned the default, params, ref and out parameter kinds. Default adds flexibility at the call, params takes a variable number of arguments, ref changes by reference, and out returns multiple values.
Now we will combine them into a small calculation method. Summation with params and a divide that returns both quotient and remainder via out will come together.
Exercise Sum five numbers with params
Define a static int Sum(params int[] nums) method; sum with foreach and return the result. In Main, call Sum(1, 2, 3, 4, 5) and print the result with Console.WriteLine.
Show example solution
Add int total = 0; foreach (int n in nums) total += n; return total; to the Sum body, write Console.WriteLine(Sum(1, 2, 3, 4, 5)); in Main.
Example solution:
using System;
class Program
{
static int Sum(params int[] nums)
{
// Sum with foreach
int total = 0;
foreach (int n in nums) total += n;
return total;
}
static void Main()
{
// Call Sum and print
Console.WriteLine(Sum(1, 2, 3, 4, 5));
}
}
Exercise Divide with out
Define static void Divide(int a, int b, out int q, out int r); in the body assign q = a / b; and r = a % b;. In Main, call Divide(20, 6, out int q, out int r) and print q with Console.WriteLine.
Show example solution
Add q = a / b; and r = a % b; to the Divide body, write Divide(20, 6, out int q, out int r); Console.WriteLine(q); in Main.
Example solution:
using System;
class Program
{
static void Divide(int a, int b, out int q, out int r)
{
// Assign q and r
q = a / b;
r = a % b;
}
static void Main()
{
// Call Divide and print q
Divide(20, 6, out int q, out int r);
Console.WriteLine(q);
}
}
Test yourself
-
Match the concepts
- default
- Default value
- params
- Variable args
- ref
- By reference
- out
- Output parameter
-
What does Console print after Double(ref x)?
static void Double(ref int n) { n *= 2; }
int x = 5;
Double(ref x);
Console.WriteLine(x);
Show answer
10 — Correct. With ref, x itself was changed; x = 10.
-
ref call
int x = 4;
Double(____);
Console.WriteLine(x);
Show answer
int x = 4;
Double(ref x);
Console.WriteLine(x);
Next lesson: Task model