Lesson 77 min read
Methods
Write once, use everywhere — the power of reusable code
What Is a Method?
A method is a recipe. You give it a name ("MakePancakes"), list the ingredients it needs (parameters), and write the steps (the body). Then, whenever you want pancakes, you just call the recipe by name instead of rewriting all the steps.
Methods help you:
- Avoid repetition — write it once, call it 100 times
- Organize code — break big problems into small, named chunks
- Test easily — you can test each method on its own
When you call a method, C# pushes it onto the call stack; when it returns, it pops off. Every method has a return type (what it gives back) and can take parameters (what you give it). If it doesn't return anything, its return type is void.
Basic Methods
Parameters: ref, out, and Optional
Normally, when you pass a variable to a method, C# sends a copy. The method can't change the original. But sometimes you want the method to modify the original — that's where ref and out come in.
ref— "I'm lending you my actual variable. You can read AND change it." The variable must be initialized before passing.out— "I'm giving you an empty box. You MUST fill it." The variable doesn't need to be initialized before passing.- Optional parameters — parameters with default values. If the caller doesn't provide them, the default kicks in.
ref, out, and Optional Parameters
Method Overloading — Same Name, Different Signatures
Note: 🎯 Expression-bodied members (=>) are perfect for one-liner methods. But if your method has more than one statement, use the regular { } block. Don't cram complex logic into an arrow — readability wins over cleverness.