Methods
Lesson 6 โข Intermediate Track
What You'll Learn
- Define methods with parameters and return values (void, int, string, etc.)
- Use expression-bodied members (=>) for concise one-liner methods
- Work with optional parameters, named arguments, and params arrays
- Return multiple values using out parameters
- Understand method overloading โ same name, different parameter signatures
- Write recursive methods (factorial, Fibonacci) with base cases
๐ก Real-World Analogy
Methods are like kitchen appliances. A blender (method) takes ingredients (parameters), processes them, and gives you a smoothie (return value). A toaster takes bread, toasts it, and returns toast โ you don't need to know how the heating element works inside (abstraction). Overloading is like a multi-function cooker: same appliance name, but it bakes, steams, or pressure-cooks depending on what settings (parameters) you give it.
๐ Method Syntax Quick Reference
| Feature | Syntax | Example |
|---|---|---|
| Void method | static void Name() | No return value |
| Return value | static int Name() | Must use return |
| Expression body | static int Name() => expr; | One-liner shorthand |
| Optional param | void F(int x = 5) | Default value if omitted |
| Params array | void F(params int[] nums) | Variable argument count |
| Out parameter | bool F(out int result) | Return multiple values |
| Named args | F(name: "Bob", age: 25) | Specify by name |
1. Defining & Calling Methods
A method has a return type, name, and parameters. Use void when it doesn't return a value, or a type like int, string, double when it does. Expression-bodied methods (=>) are perfect for simple one-liners.
Basic Methods
Create void methods, return values, and expression-bodied methods.
using System;
class Program
{
// Void method โ no return value
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}! ๐");
}
// Method with return value
static int Add(int a, int b)
{
return a + b;
}
// Expression-bodied method (one-liner)
static double CircleArea(double radius) => Math.PI * radius * radius;
// Method with multiple returns
static string GetGrade(int score)
{
if (score >= 90) return "A";
...2. Parameters โ Optional, Named, Params & Out
Optional parameters have default values. Named arguments let you specify parameters in any order. params accepts a variable number of arguments. out lets a method return multiple values โ used heavily in TryParse patterns.
Advanced Parameters
Use optional params, named args, params arrays, and out parameters.
using System;
class Program
{
// Optional parameters (must be last)
static void PrintMessage(string msg, int times = 1, string prefix = "โ")
{
for (int i = 0; i < times; i++)
Console.WriteLine($"{prefix} {msg}");
}
// Params keyword โ variable number of arguments
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int n in numbers)
total += n;
return total;
}
// Out parameter โ return multip
...3. Overloading & Recursion
Method overloading means multiple methods with the same name but different parameter types or counts โ the compiler picks the right one. Recursion is when a method calls itself; it must have a base case to stop, or it causes a stack overflow.
Overloading & Recursion
Overload methods by signature and write recursive algorithms.
using System;
class Program
{
// Method overloading โ same name, different parameters
static int Multiply(int a, int b) => a * b;
static double Multiply(double a, double b) => a * b;
static int Multiply(int a, int b, int c) => a * b * c;
// Practical: formatting helper
static string Format(int number) => number.ToString("N0");
static string Format(double number) => number.ToString("F2");
static string Format(decimal money) => money.ToString("C");
// Recursi
...Pro Tips
- ๐ก Keep methods short: A good method does one thing. If it's over 20 lines, consider splitting it.
- ๐ก Use tuples instead of out for simple cases:
static (int min, int max) GetRange(int[] arr)is often cleaner than out parameters. - ๐ก Prefer expression-bodied syntax for simple methods:
static bool IsEven(int n) => n % 2 == 0;is clean and readable. - ๐ก Avoid deep recursion: C# has a limited stack size (~1MB). For large inputs, convert recursion to iteration or use tail-call patterns.
Common Mistakes
- Forgetting return: A method declared as
static int Add()must usereturnin every code path. The compiler will catch this. - Optional params not last:
void F(int x = 5, string name)won't compile โ optional parameters must come after required ones. - Return type mismatch:
static int GetName()returning a string will cause a compile error. Match the return type to what you actually return. - Missing base case in recursion:
Factorial(n)withoutif (n <= 1) return 1;recurses forever and crashes withStackOverflowException. - Overloading by return type only: C# doesn't allow two methods with the same name and parameters but different return types. Parameters must differ.
๐ Lesson Complete
- โ Methods organise code into reusable blocks with parameters and return values
- โ
voidmethods perform actions; typed methods return values withreturn - โ
Expression-bodied syntax (
=>) for concise one-liner methods - โ
Optional parameters, named arguments,
paramsarrays, andoutparameters - โ Method overloading: same name, different parameter signatures
- โ Recursion: a method that calls itself with a base case to stop
- โ Next lesson: Object-Oriented Programming โ classes, objects, and encapsulation
Sign up for free to track which lessons you've completed and get learning reminders.