<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Arrays and methods
All lessons in this course

Lesson 13 of 60 15 minBeginner

Methods and the call stack

Package code into reusable methods with parameters and return values, and see how the call stack runs them.

A method is a named block of code that does one job. You write it once and call it whenever you need it. Methods make programs shorter, easier to read and easier to fix: a bug fixed in a method is fixed everywhere it is used.

Anatomy of a method

Area.cs
//  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));
Output
10
30
PartMeaning
staticcan be called without creating an object (explained in the OOP module)
return typethe type of value it gives back, or void for nothing
namePascalCase verb phrase: CalculateTax, PrintReport
parametersinputs the method needs, each with a type
returnends the method and hands a value back

Parameters vs arguments

Parameters are the variables in the method definition (width, height). Arguments are the actual values you pass in the call (4, 2.5). Arguments are matched to parameters by position.

void methods

Program.cs
static void PrintLine(char symbol, int length){    Console.WriteLine(new string(symbol, length));} PrintLine('=', 20);Console.WriteLine("  REPORT");PrintLine('=', 20);
Output
====================
  REPORT
====================

What happens when you call a method

The CLR keeps a call stack. Each call pushes a frame holding that call’s parameters and local variables. When the method returns, its frame is popped and those variables disappear. Step through a program that calls methods inside methods:

Interactive

Watch the call stack

Each method call gets its own frame with its own variables, stacked on top. When the method returns, its frame is removed.

Program.cs
static int Square(int x){    int result = x * x;    return result;} static int SumOfSquares(int a, int b){    int s = Square(a) + Square(b);    return s;} static void Main(){    int total = SumOfSquares(3, 4);    Console.WriteLine(total);}
Call stack (top = running now)
Main()
total = ?
Step 1 / 11
The program starts in Main. Main gets the first frame on the stack. It needs SumOfSquares(3, 4) to set total.

Expression-bodied methods

Program.cs
static int Square(int x) => x * x;static bool IsEven(int n) => n % 2 == 0; Console.WriteLine(Square(7));Console.WriteLine(IsEven(7));
Output
49
False

Overloading: same name, different parameters

Program.cs
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 version
Output
5
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.
Quick check

What does a void method return?

Quick check

Method A calls B, and B calls C. While C is running, how many frames for these methods are on the call stack?

Practice

Write a method 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

Numbers below 2 are not prime. Try dividing n by every number from 2 up to the square root of n; if any divides exactly, it is not prime.

Show the solution
Solution.cs
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 + " ");}
Output
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.
0 of 60 lessons completed