Methods and Parameters
Parameters
Parameters let a method receive values from its caller.
parameter
A parameter is a named input inside a method.
Parameters
Parameters.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static int Area(int width, int height)
{
return width * height;
}
static void Main()
{
int width = 5;
int height = 4;
int area = Area(width, height);
Console.WriteLine($"width={width}");
Console.WriteLine($"height={height}");
Console.WriteLine($"area={area}");
}
}
using System;
class Program
{
static int Area(int width, int height)
{
return width * height;
}
static void Main()
{
int width = 3;
int height = 4;
int area = Area(width, height);
Console.WriteLine($"width={width}");
Console.WriteLine($"height={height}");
Console.WriteLine($"area={area}");
}
}
using System;
class Program
{
static int Area(int width, int height)
{
return width * height;
}
static void Main()
{
int width = 7;
int height = 4;
int area = Area(width, height);
Console.WriteLine($"width={width}");
Console.WriteLine($"height={height}");
Console.WriteLine($"area={area}");
}
}
width ← 5, height ← 4
10static void Main()11{12 int width→ 5 = 5; //@width=3, 713 int height→ 4 = 4;14 int area = Area(width5, height4);static int Area(int width, int height)
4{5 static int Area(int width5, int height4)6 {7 return width5 * height4;8 }area ← 20
13 int height = 4;14 int area→ 20 = Area(width5, height4);1516 Console.WriteLine($"width={width5}");17 Console.WriteLine($"height={height4}");18 Console.WriteLine($"area={area20}");19}outputwidth=5 height=4 area=20
width ← 3, height ← 4
10static void Main()11{12 int width→ 3 = 3;13 int height→ 4 = 4;14 int area = Area(width3, height4);static int Area(int width, int height)
4{5 static int Area(int width3, int height4)6 {7 return width3 * height4;8 }area ← 12
13 int height = 4;14 int area→ 12 = Area(width3, height4);1516 Console.WriteLine($"width={width3}");17 Console.WriteLine($"height={height4}");18 Console.WriteLine($"area={area12}");19}outputwidth=3 height=4 area=12
width ← 7, height ← 4
10static void Main()11{12 int width→ 7 = 7;13 int height→ 4 = 4;14 int area = Area(width7, height4);static int Area(int width, int height)
4{5 static int Area(int width7, int height4)6 {7 return width7 * height4;8 }area ← 28
13 int height = 4;14 int area→ 28 = Area(width7, height4);1516 Console.WriteLine($"width={width7}");17 Console.WriteLine($"height={height4}");18 Console.WriteLine($"area={area28}");19}outputwidth=7 height=4 area=28
Follow the Parameters
widthstarts as5.heightstarts as4.Area(width, height)passes both values into the method.- Inside
Area,width * heightgives20. - The caller stores that result in
area. | value passed | parameter | result part | | --- | --- | --- | | 5 |width|5 * 4| | 4 |height|5 * 4| | returned value |area| 20 |
Exercise: Parameters.cs
Reproduce width=5, height=4, and area=20, then use the pinned width variants 3 and 7 to predict area=12 and area=28.