Beginner · Decisions, loops and methods · topic 9 of 43 · 30 min
Parameters in depth: optional, named, ref, out, params, overloading
Explanation
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.
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)); // 1250Named 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.
Console.WriteLine(TicketPrice(800m, meal: true)); // 950: skip quota, set meal
Console.WriteLine(TicketPrice(baseFare: 500m, quota: "Tatkal"));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.
int marks = 70;
AddGrace(marks);
Console.WriteLine(marks); // still 70
static void AddGrace(int m)
{
m += 5; // changes only the copy
}ref: share the caller's variable
int marks = 70;
AddGrace(ref marks);
Console.WriteLine(marks); // 75
static void AddGrace(ref int m)
{
m += 5;
}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.
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;
}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
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;
}Overloading: one name, different parameter lists
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| Keyword | Caller must set it first? | Method must set it? | Typical use |
|---|---|---|---|
| (none) | Yes | No | Normal inputs (a copy) |
| ref | Yes | No | Change the caller's variable |
| out | No | Yes | Extra results, TryParse pattern |
| in | Yes | Cannot change it | Avoid copying big structs |
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
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.
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;
}Practice (0/4 done)
static int Power(int b, int e = 2) { ... returns b to the power e } What does Power(3) return?
What does this print? int x = 10; Change(x); Console.WriteLine(x); static void Change(int v) { v = 99; }
What does this print? int x = 10; Change(ref x); Console.WriteLine(x); static void Change(ref int v) { v = 99; }
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loops: for, while, do-while and foreachDecisions, loops and methods · same module
- Decisions: if, else, switch and switch expressionsDecisions, loops and methods · same module
- Methods: parameters, return values and overloadingJava Programming (Core to Spring Boot) · Control flow and methods
- FunctionsKotlin and Android App Development · Null safety, functions and lambdas
- Overloading, default arguments and recursionC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Functions and multiple return valuesGo Programming (backend and cloud) · Control flow and functions
Questions people ask about this
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.
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.
Does Go support default parameter values?Related
Answer: No
Go has no default values or overloading; use different function names or an options struct.
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
- This is the last topic of “Decisions, loops and methods”. The module exam comes next.
- Module 2 exam: Decisions, loops and methods · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Arrays, strings and null. 43 topics left in the course before the final exam.