Lesson 5 · ~12 min · ← Lesson 4
Methods: naming a recipe
A method is a named block of code with inputs (parameters) and — usually — one output (a return value). Write the recipe once, use it everywhere.
Return: a method that answers a question
int Add(int a, int b)
{
return a + b; // hand this value back to the caller
}
Console.WriteLine(Add(3, 4));
Read the signature left to right: int (what comes back) Add (the name) (int a, int b) (what goes in). The caller's Add(3, 4) becomes the value 7 — it can go anywhere a value can.
void: a method that does, not answers
void Greet(string name)
{
Console.WriteLine("Hello, " + name + "!");
}
Greet("Ada");
Greet("Grace");
void means "nothing comes back" — the method acts, then control returns to the caller. A return; with no value still exits early if you need it to.
Multiple returns, one answer
A method returns the FIRST return it reaches — early returns beat deep nesting:
string Describe(int score)
{
if (score >= 90) return "excellent";
if (score >= 70) return "good";
return "keep practicing";
}
Console.WriteLine(Describe(95));
Console.WriteLine(Describe(75));
Console.WriteLine(Describe(30));
Default values: optional parameters
void Greet(string name, string greeting = "Hello")
{
Console.WriteLine(greeting + ", " + name + "!");
}
Greet("Ada"); // greeting uses its default
Greet("Bob", "Hi"); // and can be overridden
out: a method that answers TWO questions
Return gives you one value. When a method must produce a value and report success/failure — the real-world pattern behind int.TryParse — use out:
bool TryDouble(int x, out int doubled)
{
doubled = x * 2; // the method MUST assign out params
return x < 100; // ...and reports whether the value is usable
}
if (TryDouble(21, out int result))
{
Console.WriteLine("doubled: " + result);
}
Recursion: a method that calls itself
int Fib(int n)
{
if (n < 2) return n; // base case: stops the self-calling
return Fib(n - 1) + Fib(n - 2);
}
Console.Write(Fib(10));
Every recursion needs a base case (the stopping condition) — without one, the calls never end and you get a StackOverflowException. The engine here stops you at ~900 nested calls, same idea as the real runtime.
Arguments gone wrong
Call with the wrong count and the compiler stops you before anything runs — CS1501 / CS7036 are the codes you'll see, and argument-count mismatches are the most common trigger.
Practice this now
- Write
int Max3(int a, int b, int c)using the running-maximum pattern from Lesson 4 — onereturn, no library calls. Then check it against the graded problem. - Write
int SumDigits(int n)with the% 10 / 10loop — a method wrapping the exact pattern from Count the Digits. - Next lesson: Lesson 6 — Classes & objects, where methods get a home.