C# Methods
Package reusable logic in a static method.
On this page
C# basics and expressions.
- Package reusable logic in a static method.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
using System;
class Program {
static int Square(int n) {
return n * n;
}
static void Main() {
Console.WriteLine(Square(4));
Console.WriteLine(Square(Square(2)));
}
}16 16
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
using System; class Program { static int Square(int n) { return n * n; } static void Main() { Console.WriteLine(Square(4)); Console.WriteLine(Square(Square(2))); }}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 |
Behind the scenes
How C# processes this code
C# compiles to code for the .NET runtime, which invokes the program entry point.
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.