Methods and parameters
Methods group reusable code, and their signatures describe what goes in and out.
- Return a value or void; never mix the two by surprise.
- Use optional parameters and named arguments for readable defaults.
- Reserve out and ref for the rare case you need extra outputs.
- Overload by parameter list, not by return type alone.
In plain English
A method groups a reusable block of code behind a name, and its return type declares what it gives back. void returns nothing, while a concrete type promises a value. Optional parameters supply defaults, and named arguments let you skip or reorder them. out and ref pass arguments by reference so a method can return extra values, and overloading lets one method name have several signatures.
Step by step
- 1Write a method with a return type and call it.
- 2Add an optional parameter and call with a named argument.
- 3Add an overload with a different parameter list.
- 4Use out and ref to return extra values.
public class Lesson
{
public string Describe(string title, int minutes = 10)
{
return title + " takes " + minutes + " minutes";
}
public string Describe(string title)
{
return "No duration set for " + title;
}
public void Track(string title, out int slot, ref int seen)
{
slot = seen;
seen += 1;
}
}
var lesson = new Lesson();
var summary = lesson.Describe("C#", minutes: 12);
var shortSummary = lesson.Describe("HTML");
int slot;
var seen = 0;
lesson.Track("C#", out slot, ref seen);
Console.WriteLine(summary);
Console.WriteLine(slot);Common mistakes
- You cannot overload two methods that differ only in their return type.
- An out parameter must be assigned before the method returns.
- A ref argument must be initialized before it is passed in.
- Stacking too many optional parameters makes call sites hard to read.
Overload a formatting method
Write two overloads of a method named Describe: one taking a string title, and one taking a string title and an int minutes.
public class Lesson
{
public string Describe(string title)
{
return title;
}
}Which must be true to overload a method?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.