$ dotnet run15a + bAdd(a, b)1int x = Add(2, 3);2int y = Add(x, 10);3Console.WriteLine(y);45static int Add(int a, int b)6{7 return a + b;8}call stack↑ newer frames go on topAdd framea–b–top-level framex–y–2355101515
Program.cs: the calls and the method AddThe call stack: one frame per running callTokens: argument and return values movingFront left: Program.cs, three statements that call the method Add, then the method itself. Back: the console and the method Add. Right: the call stack, with the top-level frame (x, y) and, during a call, Add's frame (a, b) on top. Each call copies its arguments into a and b, the body adds them, return sends the sum back into x or y, and the frame goes away; finally 15 is printed. The call stack here is simplified: a real frame also holds the return address and other bookkeeping, and the JIT compiler may keep small values like a and b in CPU registers or inline a tiny method like Add.

Defining a method

  1. A method is a named block of code that does one job. You write it once, then run it by its name as often as you need. Lines 5 to 8 define a method called Add.

Calling it

Methods everywhere

What happens

// step 1/9 · method
1  int x = Add(2, 3);
2  int y = Add(x, 10);
3  Console.WriteLine(y);
4  
5  static int Add(int a, int b)
6  {
7      return a + b;
8  }

lines 1-3   top-level statements: they run first, top to bottom
lines 5-8   the method Add: it only runs when it is called

The call stack here is simplified: a real frame also holds the return address and other bookkeeping, and the JIT compiler may keep small values like a and b in CPU registers or inline a tiny method like Add. With top-level statements, a method written in Program.cs is strictly a local function; the compiler turns it into an ordinary method. static means it cannot use the top-level variables x and y, only its own parameters. In larger programs methods live inside a class.