Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Declaring methods

โญ beginnerโณ 14 min read๐Ÿ“ Lesson 18 of 85

The anatomy of a method: parameters, return types, void, and expression-bodied shorthand.

A method is a named computation

static double Total(double price, int quantity)
{
    return price * quantity;
}

Read the pieces: static (belongs to the type, not an object โ€” you've called Console.WriteLine the same way), double (the return type โ€” what comes back), Total (the name โ€” a verb phrase is the convention), and the parameter list (double price, int quantity) โ€” named inputs the body may use like local variables.

return hands back the value and exits immediately โ€” code after a return in the same path never runs. A method whose return type is not void must return on every path; the compiler enforces this ("not all code paths return a value").

void: action, not answer

static void Greet(string name)
{
    Console.WriteLine("Hello, " + name + "!");
}

void means "I produce no value โ€” I do something." Calling a void method as a statement is fine; calling a value-returning method and ignoring the result is legal but usually a smell. Don't fake returns: Greet returning nothing is honest; returning true "because it worked" is not.

Expression-bodied members

static int Square(int x) => x * x;
static bool IsAdult(int age) => age >= 18;

When the body is one expression, => expression replaces the braces and the return. Same semantics, less ceremony. Rule of thumb: if it reads like a formula, use the expression body; if it needs steps or conditionals with side effects, use a block.

Why methods at all

Three reasons, in order of importance: a name documents intent (Total(price, qty) beats an unexplained price * qty); reuse means the formula lives in exactly one place โ€” fix the bug once; testability means a method with inputs and an output can be graded by code โ€” exactly what every challenge in this course does.