SkillPilotAI

Methods and parameters

Methods package reusable logic, and parameters decide how data goes in and out. Knowing pass-by-value vs ref/out/in, params, optional and named arguments, overloading, local functions and recursion covers most method questions in C# interviews.

10.1 Problem: 600 inside, 500 outside

C#
int points = 500;AddBonus(points);Console.WriteLine($"Points: {points}"); void AddBonus(int p){    p += 100;    Console.WriteLine($"Inside: {p}");}
Output
$ dotnet run Bonus.csInside: 600Points: 500
Why the bonus was lost
  1. 1.points = 500 in the caller's box

  2. 2.AddBonus(points): p gets a copy (500) in its own box

  3. 3.p += 100: only the copy becomes 600

  4. 4.Method ends: the copy is gone

  5. 5.points is still 500

By default arguments are passed by value: the method gets a copy

10.2 Fix 1: return the value

  • The cleanest fix: the method returns the new result and the caller stores it.
  • Expression-bodied method: int Double(int p) => p * 2; writes the result after the arrow.
C#
int points = 500;points = AddBonus(points);Console.WriteLine($"Points: {points}"); int AddBonus(int p){    return p + 100;} int Double(int p) => p * 2;Console.WriteLine(Double(points));
Output
$ dotnet run Bonus.csPoints: 6001200

10.3 Fix 2: ref and out

  • ref: write it at the declaration and at the call; the method works on the caller's original variable.
  • out: the method must assign it before returning; out int off declares the variable at the call.
  • out is the TryParse pattern: return success as bool, the result through out.
C#
int points = 500;AddBonus(ref points);Console.WriteLine($"Points: {points}"); if (TryCoupon("SAVE10", out int off))    Console.WriteLine($"Off: {off}%"); void AddBonus(ref int p) => p += 100; bool TryCoupon(string code, out int percent){    percent = code == "SAVE10" ? 10 : 0;    return percent > 0;}
Output
$ dotnet run RefOut.csPoints: 600Off: 10%

10.4 Comparison: normal vs ref vs out vs in

KindPassed asCaller must assign first?Method can change it?Typical use
normalCopy (by value)YesOnly its copyDefault for everything
refReferenceYesYes (read + write)Really need to change the caller's variable
outReferenceNoMust assign before returnTryParse-style methods
inRead-only referenceYesNoBig structs without copying

10.5 params, optional and named arguments

  • params decimal[] prices: any number of arguments; the compiler builds the array (zero arguments = empty array).
  • Optional parameters have defaults (seats = 1, ac = false) and can be left out.
  • Named arguments (ac: true) skip optional parameters and keep calls readable.
C#
decimal Total(params decimal[] prices){    decimal sum = 0;    foreach (decimal p in prices) sum += p;    return sum;}string Ticket(string from, string to,    int seats = 1, bool ac = false) =>    $"{from}-{to}, seats {seats}, AC {ac}"; Console.WriteLine(Total(499, 1299, 250));Console.WriteLine(Total());Console.WriteLine(Ticket("Delhi", "Agra"));Console.WriteLine(Ticket("Delhi", "Agra", ac: true));
Output
$ dotnet run Booking.cs20480Delhi-Agra, seats 1, AC FalseDelhi-Agra, seats 1, AC True

10.6 Method overloading

  • Same name, different parameters (number or types).
  • The compiler picks the version from the arguments: Of(4), Of(4, 5), Of(1.5).
  • A different return type alone does not make an overload.
C#
Console.WriteLine(Area.Of(4));Console.WriteLine(Area.Of(4, 5));Console.WriteLine(Area.Of(1.5)); static class Area{    public static int Of(int s) => s * s;    public static int Of(int w, int h) => w * h;    public static double Of(double r) =>        Math.Round(Math.PI * r * r, 2);}
Output
$ dotnet run Area.cs16207.07

10.7 Local functions

  • A method written inside another method, used only there.
  • static local function: cannot accidentally use outer variables.
  • Methods written in top-level code are actually local functions too.
C#
Console.WriteLine(FinalPrice(499, 3));Console.WriteLine(FinalPrice(499, 0)); decimal FinalPrice(decimal price, int qty){    Check(price);    Check(qty);    return price * qty;     static void Check(decimal value)    {        if (value <= 0)            throw new ArgumentException("Must be > 0");    }}
Output
$ dotnet run Price.cs1497Unhandled exception. System.ArgumentException: Must be > 0

10.8 Recursion

  • A method that calls itself; each call makes the problem smaller.
  • The base case (n <= 1 returns 1) stops the recursion.
  • Factorial(20) is huge, so the return type is long.
C#
long Factorial(int n){    if (n <= 1)        return 1;          // base case    return n * Factorial(n - 1);} Console.WriteLine(Factorial(5));Console.WriteLine(Factorial(20));
Output
$ dotnet run Factorial.cs1202432902008176640000
How Sum(4) unwinds
  1. 1.Sum(4) = 4 + Sum(3)

  2. 2.Sum(3) = 3 + Sum(2)

  3. 3.Sum(2) = 2 + Sum(1)

  4. 4.Sum(1) = 1 + Sum(0)

  5. 5.Sum(0) hits the base case: returns 0

  6. 6.Results return up the stack: 0, 1, 3, 6, 10

Checkpoint: Sum(4) prints 10

C#
int Sum(int n){    if (n == 0) return 0;    return n + Sum(n - 1);} Console.WriteLine(Sum(4));

10.9 Common mistakes

  • Forgetting the base case: the method calls itself forever, the call stack fills up and the program crashes with Stack overflow.
  • Expecting a normal int parameter change to reach the caller: return the value or use ref.
  • Myth: arrays are passed by reference. Everything is passed by value; for reference types a copy of the reference is passed.
  • So a change inside the array is seen by the caller, but assigning a new array to the parameter is not.
  • Overloads that behave differently: keep all overloads consistent.

10.10 Interview tips

  • ref, out and in all pass by reference.
  • ref: must be assigned first, method can read and change. out: caller need not initialize, method must assign before returning.
  • in: read-only reference, used to pass big structs without copying.
  • By default everything (even reference types) is passed by value.
  • Prefer return values; keep out for the TryParse pattern and ref for rare cases.