Summary - Methods
Combine overloading and local functions to write a math helper class.
Summary - Methods
In this section you learned method declaration, return, void, overloading and local functions. Methods let you name code and call it again; overloading lets you use the same name with different parameters.
Now we will combine them into a small math helper. Overloading will give two- and three-parameter sums, and a local function will compute squares.
Exercise Add and Multiply
Define two methods: static int Add(int a, int b) { return a + b; } and static int Multiply(int a, int b) { return a * b; }. In Main, compute int result = Add(2, 3) + Multiply(4, 5); and print result with Console.WriteLine.
Show example solution
Add both methods, write int result = Add(2, 3) + Multiply(4, 5); Console.WriteLine(result); in Main.
Example solution:
using System;
class Program
{
// Define Add and Multiply methods
static int Add(int a, int b) { return a + b; }
static int Multiply(int a, int b) { return a * b; }
static void Main()
{
// Combine Add and Multiply calls and print
int result = Add(2, 3) + Multiply(4, 5);
Console.WriteLine(result);
}
}
Exercise Square with a local function
Define a static void Run() method. In its body declare int Square(int n) { return n * n; } and print with Console.WriteLine(Square(7));. Call Run() from Main.
Show example solution
In the Run body add int Square(int n) { return n * n; } and Console.WriteLine(Square(7));, write Run(); in Main.
Example solution:
using System;
class Program
{
static void Run()
{
// Declare Square as a local function and print its result
int Square(int n) { return n * n; }
Console.WriteLine(Square(7));
}
static void Main()
{
// Call Run
Run();
}
}
Test yourself
-
What does Square(6) print?
static int Square(int n) { return n * n; } Console.WriteLine(Square(6));- 12
- 36
- 6
- 0
Show answer
36 — Correct. Square(6) = 6*6 = 36.
-
Local function call
static void Run() { int Double(int n) { return n * 2; } ____ }Show answer
static void Run() { int Double(int n) { return n * 2; } Console.WriteLine(Double(7)); } -
Match the concepts
- static int
- Returns int
- void
- No return
- return
- Yields value
- int Square(int)
- Local function