C# Methods
Package reusable logic in a static method.
C#
using System;
class Program {
static int Square(int n) {
return n * n;
}
static void Main() {
Console.WriteLine(Square(4));
Console.WriteLine(Square(Square(2)));
}
}Output
16 16
Explanation
A method has a return type, a name, parameters, and a body. static means it belongs to the class itself, which is what lets Main call it without creating an object.
The argument is evaluated before the call, so Square(Square(2)) first computes Square(2) = 4 and then passes 4 into the outer call.
Explore the dry run
Guided walkthroughReady
1
using System;2
3
class Program {4
static int Square(int n) {5
return n * n;6
}7
8
static void Main() {9
Console.WriteLine(Square(4));10
Console.WriteLine(Square(Square(2)));11
}12
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Define a method that takes an int and returns an int. | — | — | |
| n is 4, so the method returns 16. | n = 4, return = 16 | 16 | |
| The inner call returns 4, then the outer call squares it. | inner = 4, return = 16 | 16 16 |
Cost and common mistakes
O(1) time and space per call.
- int arithmetic overflows silently by default, so very large squares wrap around.
- A non-void method must return a value on every path or the code does not compile.
Try it yourself
Predict Square(-3).
Reveal answer and reasoning
A negative times a negative is positive, so it returns 9.