📝 Lesson 3.3: Methods
As programs grow, you need a way to organize them. Methods let you package a chunk of code, give it a name, and reuse it anywhere — the key to writing code that stays clean and understandable.
🎯 Learning Objectives
By the end of this lesson, you will be able to:
- Define and call your own methods
- Pass information into a method with parameters
- Get a result back from a method with a return value
- Explain variable scope: where a variable can be used
- Appreciate why methods make code reusable and readable (DRY)
Estimated Time: 60 minutes
Project: Refactor a program into tidy, reusable methods.
In This Lesson
What Is a Method?
A method is a named block of code that performs a specific task. You've been using methods all along — Console.WriteLine is a method, and so is int.Parse. Now you'll write your own.
📖 Definition
Method: A reusable, named block of code. You define it once, then call it (run it) by name as many times as you like.
Think of a method like a recipe. The recipe is written down once (the definition). Whenever you want the dish, you "follow the recipe" (call the method). You can even hand it inputs — ingredients (parameters) — and get a result back — the finished dish (return value).
(parameters)"] --> B["Method
(does the work)"] B --> C["Output
(return value)"] style A fill:#eff6ff,stroke:#3b82f6,stroke-width:2px style C fill:#e8f5e9,stroke:#4CAF50,stroke-width:2px
Defining and Calling
The simplest method takes no input and returns nothing — it just does a task. The keyword void means "returns nothing":
// Define the method
void Greet()
{
Console.WriteLine("Hello there!");
Console.WriteLine("Welcome to the program.");
}
// Call it (as many times as you like)
Greet();
Greet();
Output:
Hello there!
Welcome to the program.
Hello there!
Welcome to the program.
The anatomy of that definition:
void— the return type;voidmeans it gives nothing back.Greet— the method name. By convention, method names use PascalCase (each word capitalized).()— the parameter list, empty here (no inputs).{ ... }— the body: the code that runs when you call it.
💡 Define vs. call
Defining a method just describes what it would do — it doesn't run anything yet. The code only executes when you call it with Greet();. It's like the difference between writing a recipe and actually cooking.
Parameters: Passing Data In
Methods become far more useful when you can feed them different data. Parameters are variables listed in the parentheses that receive the values you pass in (those values are called arguments):
// 'name' is a parameter
void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Greet("Ada"); // "Ada" is the argument
Greet("Grace");
Greet("Alan");
Output:
Hello, Ada!
Hello, Grace!
Hello, Alan!
One definition, three different results — that's the power of parameters. You can have several, separated by commas:
void Describe(string name, int age)
{
Console.WriteLine($"{name} is {age} years old.");
}
Describe("Ada", 30);
Describe("Grace", 45);
⚠️ Types and order must match
The arguments you pass must match the parameters in type and order. Describe(30, "Ada") would be an error, because 30 isn't a string and "Ada" isn't an int. C#'s type safety catches this for you.
Return Values: Getting Data Out
Often you want a method to compute something and hand the result back so you can use it. Instead of void, declare the type of value the method returns, and use the return keyword to send it back:
// Returns an int
int Add(int a, int b)
{
return a + b;
}
int sum = Add(3, 4); // sum is now 7
Console.WriteLine(sum); // 7
Console.WriteLine(Add(10, 20)); // 30 — use the result directly
Here int Add(...) promises to return an int. The return a + b; line computes the value and immediately sends it back to whoever called the method. The call Add(3, 4) is then replaced by its result, 7 — just like an expression.
💡 return also exits the method
As soon as return runs, the method ends and control goes back to the caller — any code after it in the method is skipped. A void method returns automatically at the end, but you can also use a bare return; to exit early.
A method that returns a bool reads beautifully in an if:
bool IsEven(int number)
{
return number % 2 == 0;
}
if (IsEven(10))
{
Console.WriteLine("10 is even"); // this runs
}
✅ Name methods for what they do
Good method names are usually verbs or verb phrases: Add, PrintReceipt, IsEven, CalculateTotal. A reader should guess what a method does from its name alone.
Variable Scope
Scope is the region of code where a variable exists and can be used. A variable declared inside a method (including its parameters) is local to that method — it doesn't exist outside it:
int Square(int n)
{
int result = n * n; // 'result' lives only inside Square
return result;
}
Console.WriteLine(Square(5)); // 25
// Console.WriteLine(result); // ❌ Error — 'result' doesn't exist out here
💡 Why scope is a good thing
Local variables keep methods self-contained. Two methods can each have a variable named result without interfering, because each lives in its own scope. This is what lets you write and change methods independently without side effects rippling through your whole program.
💡 The rule of thumb: A variable exists only within the braces{ }where it was declared. Once you leave that block, the variable is gone. The clean way to move data out of a method is toreturnit.
Why Methods Matter (DRY)
Methods aren't just tidy — they solve real problems that grow with your program:
- Reuse: Write logic once, call it everywhere. Fixing a bug means fixing it in one place.
- Readability: A well-named method call like
CalculateTax(price)reads like a sentence and hides the messy details. - Testability: Small, focused methods are easy to reason about and check.
📖 The DRY principle
DRY = "Don't Repeat Yourself." If you find yourself copying and pasting the same lines, that's a signal to move them into a method and call it instead. Duplicated code is duplicated bugs.
Compare these two approaches to greeting three people:
// Repetitive — the same pattern copied three times
Console.WriteLine("Hello, Ada! Welcome aboard.");
Console.WriteLine("Hello, Grace! Welcome aboard.");
Console.WriteLine("Hello, Alan! Welcome aboard.");
// DRY — one method, called three times
void Welcome(string name)
{
Console.WriteLine($"Hello, {name}! Welcome aboard.");
}
Welcome("Ada");
Welcome("Grace");
Welcome("Alan");
If the greeting wording ever changes, the DRY version needs just one edit — inside the method.
Exercise & Quiz
🏋️ Exercise: Build a Toolbox of Methods
Objective: Write methods with parameters and return values, then use them together.
Instructions:
- Create a new project called
Methods. - Write a method
int Multiply(int a, int b)that returns the product of two numbers. - Write a method
bool IsPositive(int n)that returnstrueifnis greater than 0. - Write a
voidmethodPrintBanner(string text)that prints the text with a line of dashes above and below it. - Call all three from your main code and print the results.
Starter Code:
// TODO: define Multiply, IsPositive, PrintBanner
// Example calls (uncomment once your methods exist):
// PrintBanner("Method Toolbox");
// Console.WriteLine($"3 x 4 = {Multiply(3, 4)}");
// Console.WriteLine($"Is -5 positive? {IsPositive(-5)}");
💡 Hint
A returning method declares its type instead of void and uses return. For the banner, print "--------------------", then the text, then the dashes again. In top-level programs, you can define methods below your calling code — the compiler finds them.
✅ Solution
PrintBanner("Method Toolbox");
Console.WriteLine($"3 x 4 = {Multiply(3, 4)}");
Console.WriteLine($"Is -5 positive? {IsPositive(-5)}");
Console.WriteLine($"Is 8 positive? {IsPositive(8)}");
int Multiply(int a, int b)
{
return a * b;
}
bool IsPositive(int n)
{
return n > 0;
}
void PrintBanner(string text)
{
Console.WriteLine("--------------------");
Console.WriteLine(text);
Console.WriteLine("--------------------");
}
Output:
--------------------
Method Toolbox
--------------------
3 x 4 = 12
Is -5 positive? False
Is 8 positive? True
🎯 Quick Quiz
Question 1: What does the return type void mean?
Question 2: In Greet("Ada"), what is "Ada" called?
Question 3: A variable declared inside a method can be used…
Summary
🎉 Key Takeaways
- A method is a named, reusable block of code. You define it once and call it by name.
- Parameters pass data in; the actual values you pass are arguments (they must match by type and order).
- A return type (like
intorbool) plusreturnsends a result back;voidmeans nothing is returned. - Scope: variables declared in a method are local to it — use
returnto get data out. - Methods keep code DRY (Don't Repeat Yourself), readable, and easy to fix in one place.
📚 Additional Resources
🚀 What's Next?
That completes Module 3 — you can now branch, loop, and organize code into methods! In Module 4, we start working with more data at once. First up: Lesson 4.1: Collections — Arrays and Lists, which pairs perfectly with the loops and methods you just learned.
🎉 Module 3 complete!
You've mastered the core logic of programming: decisions, loops, and methods. The home stretch is about data and objects.