Skip to content

Beginner · Decisions, loops and methods · topic 9 of 43 · 30 min

Parameters in depth: optional, named, ref, out, params, overloading

Explanation

Parameters can have default values (optional parameters), and callers can name arguments to make calls clear. Normally arguments are copied in; ref lets a method change the caller's variable, and out lets it hand back extra results, as int.TryParse does. params accepts any number of values, and overloading lets several methods share one name with different parameter lists.

Optional parameters

An optional parameter has a default value written in the header. If the caller leaves it out, the default is used. Optional parameters must come after all required ones, and the default must be a constant known at compile time.

csharp
static decimal TicketPrice(decimal baseFare, string quota = "General", bool meal = false)
{
    decimal price = quota == "Tatkal" ? baseFare + 300m : baseFare;
    return meal ? price + 150m : price;
}

Console.WriteLine(TicketPrice(800m));                  // 800
Console.WriteLine(TicketPrice(800m, "Tatkal"));        // 1100
Console.WriteLine(TicketPrice(800m, "Tatkal", true));  // 1250
Leaving out arguments uses the defaults.

Named arguments

A named argument writes the parameter name and a colon before the value. Order then does not matter, and calls with many true/false options become readable.

csharp
Console.WriteLine(TicketPrice(800m, meal: true));       // 950: skip quota, set meal
Console.WriteLine(TicketPrice(baseFare: 500m, quota: "Tatkal"));
Compare TicketPrice(800m, "General", true) with TicketPrice(800m, meal: true). The second explains itself.

Passing by value: the default

By default, C# passes arguments by value: the method gets a copy. Changing the copy does not change the caller's variable.

csharp
int marks = 70;
AddGrace(marks);
Console.WriteLine(marks);    // still 70

static void AddGrace(int m)
{
    m += 5;   // changes only the copy
}
The method changed its own copy. (Objects like lists behave differently because the copy is a copy of a reference; module 4 explains.)

ref: share the caller's variable

csharp
int marks = 70;
AddGrace(ref marks);
Console.WriteLine(marks);    // 75

static void AddGrace(ref int m)
{
    m += 5;
}
ref passes the variable itself. You must write ref both in the header and at the call, and the variable must already have a value.

out: extra results

out is like ref, but for values going OUT. The caller does not need to set the variable first, and the method MUST assign it before returning. The TryParse methods use this pattern: return true or false, and give the parsed number through out.

csharp
if (TryGetDiscount("FESTIVE10", out decimal percent))
    Console.WriteLine($"Discount {percent}%");
else
    Console.WriteLine("Invalid coupon");

static bool TryGetDiscount(string code, out decimal percent)
{
    percent = code switch
    {
        "FESTIVE10" => 10m,
        "WELCOME5" => 5m,
        _ => 0m
    };
    return percent > 0;
}
out decimal percent declares the variable right inside the call.

in: read-only reference, briefly

in passes a reference that the method may read but not change. It exists to avoid copying very large structs. You will rarely need it as a beginner; just recognise it when you see it.

params: any number of arguments

csharp
Console.WriteLine(Sum(10, 20, 30));   // 60
Console.WriteLine(Sum());             // 0
int[] bills = { 250, 99, 400 };
Console.WriteLine(Sum(bills));        // 749

static int Sum(params int[] numbers)
{
    int total = 0;
    foreach (int n in numbers) total += n;
    return total;
}
params collects the arguments into an array. It must be the last parameter. Console.WriteLine and string.Format use params.

Overloading: one name, different parameter lists

csharp
static int Area(int side) => side * side;
static int Area(int length, int width) => length * width;
static double Area(double radius) => Math.PI * radius * radius;

Console.WriteLine(Area(4));       // 16
Console.WriteLine(Area(4, 5));    // 20
Console.WriteLine(Area(1.0));     // 3.141592653589793
The compiler picks the overload whose parameter types match the arguments.
Careful: Methods cannot be overloaded by return type alone. int Get() and string Get() in the same class is error CS0111. The parameter lists must differ.
KeywordCaller must set it first?Method must set it?Typical use
(none)YesNoNormal inputs (a copy)
refYesNoChange the caller's variable
outNoYesExtra results, TryParse pattern
inYesCannot change itAvoid copying big structs
Tip: Prefer returning a value (or a tuple) over ref. ref makes code harder to follow, because a call can quietly change your variables. Use out mainly for the Try... pattern.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Parameters in depth: optional, named, ref, out, params, overloading · 1/7

Parameters in depth

In this lesson you will learn all the ways to pass values into methods.

Prefer a video by a teacher? Find free videos on “C# ref out params optional named arguments method overloading” on YouTube ↗

In real life: A UPI payment helper

A payments team writes one helper to send money. Most calls use the default note and no PIN reminder, so those are optional. The method uses the Try pattern with out to return a transaction id only when the payment works.

csharp
if (TrySendUpi("asha@okbank", 450m, out string txnId, note: "Dinner split"))
    Console.WriteLine($"Paid. Txn {txnId}");
else
    Console.WriteLine("Payment failed");

static bool TrySendUpi(string toVpa, decimal amount, out string txnId, string note = "", bool remind = false)
{
    txnId = "";
    if (amount <= 0 || !toVpa.Contains('@')) return false;
    txnId = "TXN" + DateTime.Now.ToString("yyyyMMddHHmmss");
    return true;
}
A simulation only: real UPI payments go through a bank or payment app's secure API.

Practice (0/4 done)

Task 1 · Question

static int Power(int b, int e = 2) { ... returns b to the power e } What does Power(3) return?

Task 2 · Question

What does this print? int x = 10; Change(x); Console.WriteLine(x); static void Change(int v) { v = 99; }

Task 3 · Question

What does this print? int x = 10; Change(ref x); Console.WriteLine(x); static void Change(ref int v) { v = 99; }

Task 4 · Practice

Write an overloaded method Bill: Bill(decimal amount) adds 18% GST; Bill(decimal amount, decimal gstRate) uses the given rate; and a method Total(params decimal[] items) adds any number of item prices. Call Bill(Total(120m, 80m, 300m), 0.05m).

Quick quiz

Question 1

1.Which keyword means "the method must assign this before returning, and the caller need not set it"?

Question 2

2.Where must a params parameter be in the list?

Question 3

3.Can you overload two methods that differ only in return type?

Question 4

4.static void Book(string name, bool meal = false, bool window = false). Which call sets only window to true?

Question 5

5.Where must optional parameters appear?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which keyword means "the method must assign this before returning, and the caller need not set it"?

Answer: out

out parameters are for results flowing out of the method.

Where must a params parameter be in the list?

Answer: Last

params must be the last parameter, so the compiler knows which arguments belong to it.

Can you overload two methods that differ only in return type?

Answer: No, the parameter lists must differ

The compiler chooses an overload by arguments, so return type alone is not enough (CS0111).

static void Book(string name, bool meal = false, bool window = false). Which call sets only window to true?

Answer: Book("Asha", window: true)

A named argument skips meal (default false) and sets window.

Where must optional parameters appear?

Answer: After all required ones

Required parameters come first, then the optional ones with defaults.

Is Java pass-by-value or pass-by-reference?Related

Answer: Always pass-by-value (references are copied for objects)

Java copies every argument; for objects, the copy is the reference.

From Methods: parameters, return values and overloading

Why are named arguments useful?Related

Answer: They make calls with many parameters clear and order-independent

Names document what each value means.

From Functions

When does the compiler choose which overload to call?Related

Answer: At compile time, from the argument types

Overload resolution happens while compiling, based on the arguments in each call.

From Overloading, default arguments and recursion

Does Go support default parameter values?Related

Answer: No

Go has no default values or overloading; use different function names or an options struct.

From Functions and multiple return values

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Decisions, loops and methods”. The module exam comes next.
  2. Module 2 exam: Decisions, loops and methods · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Arrays, strings and null. 43 topics left in the course before the final exam.

← Previous: Methods: write once, use many times