C# · Course navigation

C# Methods

Package reusable logic in a static method.

On this page
Before you start

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1using System;
2
3class 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading