Methods and the call stack
Package code into reusable methods with parameters and return values, and see how the call stack runs them.
Anatomy of a method
// return type name parametersstatic double RectangleArea(double width, double height){ double area = width * height; return area; // send the result back to the caller} double a = RectangleArea(4, 2.5); // call it with argumentsConsole.WriteLine(a);Console.WriteLine(RectangleArea(10, 3));10 30
| Part | Meaning |
|---|---|
static | |
void for nothing | |
CalculateTax, PrintReport | |
return |
Parameters vs arguments
width, height). Arguments are the actual values you pass in the call (4, 2.5). Arguments are matched to parameters by position.
void methods
static void PrintLine(char symbol, int length){ Console.WriteLine(new string(symbol, length));} PrintLine('=', 20);Console.WriteLine(" REPORT");PrintLine('=', 20);==================== REPORT ====================
What happens when you call a method
Expression-bodied methods
static int Square(int x) => x * x;static bool IsEven(int n) => n % 2 == 0; Console.WriteLine(Square(7));Console.WriteLine(IsEven(7));49 False
Overloading: same name, different parameters
static int Add(int a, int b) => a + b;static double Add(double a, double b) => a + b;static int Add(int a, int b, int c) => a + b + c; Console.WriteLine(Add(2, 3)); // int versionConsole.WriteLine(Add(2.5, 1.2)); // double versionConsole.WriteLine(Add(1, 2, 3)); // three-parameter version5 3.7 6
Good method habits
One method, one job. If you need “and” to describe it, split it. Keep methods short: ideally they fit on one screen. Name methods with verbs: GetTotal,ValidateInput,SaveFile.Return results instead of printing inside calculation methods, so they can be reused.
static bool IsPrime(int n) that returns true if n is a prime number, then print all primes from 1 to 30 using a loop.
Show a hint
Show the solution
static bool IsPrime(int n){ if (n < 2) return false; for (int d = 2; d * d <= n; d++) { if (n % d == 0) return false; } return true;} for (int i = 1; i <= 30; i++){ if (IsPrime(i)) Console.Write(i + " ");}2 3 5 7 11 13 17 19 23 29
Remember
A method is reusable code: returnType Name(parameters) { ... return value; }.Parameters are placeholders; arguments are the values passed in the call. Each call gets a stack frame for its locals, removed when it returns. Overloads share a name but have different parameter lists.