C# Foundations·C# from first file to first API

Methods and parameters

Methods group reusable code, and their signatures describe what goes in and out.

Beginner 12 min read Lesson 2 of 300 Challenge included
What you will be able to do
  • 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

  1. 1Write a method with a return type and call it.
  2. 2Add an optional parameter and call with a named argument.
  3. 3Add an overload with a different parameter list.
  4. 4Use out and ref to return extra values.
Lesson.csC#
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.
Your turn

Overload a formatting method

Medium

Write two overloads of a method named Describe: one taking a string title, and one taking a string title and an int minutes.

CSHARP · starter
public class Lesson
{
    public string Describe(string title)
    {
        return title;
    }
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Which must be true to overload a method?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 2 of 300 · 0% of course