C# & .NET Framework Methods — Your Toolbox
💡
Exercise 24

ref, out & Advanced Parameters 20 XP Medium

Ctrl+Enter Run Ctrl+S Save

🔩 Advanced Tools That Modify Blueprints

So far, our tools have been read-only — they take values, compute something, and return a result. The original values stay untouched. But what if you need a tool that modifies the original? Like a power drill that doesn't just inspect the wall — it changes it.

In C#, parameters are passed by value by default, meaning the method gets a copy. But with ref, out, and in, you can pass parameters by reference, giving the method direct access to the original variable.

🔗 ref — "Let Me Modify Your Original"

The ref keyword passes a variable by reference. The method can read and modify the original variable. The variable must be initialized before passing it.

static void DoubleIt(ref int number) { number *= 2; // Modifies the ORIGINAL variable } static void Main() { int value = 10; Console.WriteLine($"Original: {value}"); // Original: 10 DoubleIt(ref value); // Pass by reference Console.WriteLine($"After DoubleIt: {value}"); // After DoubleIt: 20 }

📤 out — "I Promise to Give You a Value"

The out keyword is like ref, but with a twist: the variable does NOT need to be initialized before passing, and the method must assign a value before it returns. It's perfect for methods that need to return multiple values or try-parse patterns.

static bool TryParseBlueprint(string input, out int result) { bool success = int.TryParse(input, out result); return success; } // C# 7+ inline out variable declaration: if (TryParseBlueprint("42", out int parsed)) { Console.WriteLine($"Parsed successfully: {parsed}"); // Parsed successfully: 42 }

📚 params — "Bring as Many as You Want"

The params keyword lets a method accept a variable number of arguments of the same type. It must be the last parameter and there can be only one per method. The arguments are collected into an array automatically.

static int Sum(params int[] numbers) { int total = 0; foreach (int n in numbers) total += n; return total; } // Call with any number of arguments: Console.WriteLine(Sum(1, 2, 3, 4, 5)); // 15 Console.WriteLine(Sum(10, 20)); // 30 Console.WriteLine(Sum()); // 0 (no args = empty array)

🏷️ Named & Optional Parameters

Optional parameters have default values — if the caller doesn't provide them, the default is used. Named arguments let you specify parameters by name, making calls more readable and allowing you to skip optional parameters.

static string Greet(string title, string name = "Architect") { return $"{title}, {name}!"; } Console.WriteLine(Greet("Hello")); // Hello, Architect! Console.WriteLine(Greet("Hi", "Builder")); // Hi, Builder! Console.WriteLine(Greet(name: "Designer", title: "Welcome")); // Welcome, Designer!

🆚 ref vs out vs in — Quick Comparison

  • ref — Must be initialized before passing. Method can read and modify.
  • out — Does NOT need initialization. Method must assign a value.
  • in — Must be initialized. Method can only read (read-only reference). Great for large structs to avoid copying.
  • All three pass by reference — the method accesses the original memory location.

💡 Key Takeaways

  • By default, C# passes parameters by value — the method gets a copy.
  • ref lets a method modify the original variable (must be pre-initialized).
  • out forces the method to assign a value (no initialization needed).
  • params accepts a variable number of arguments as an array.
  • Optional parameters provide defaults; named arguments improve readability.
  • Use in for large read-only structs to avoid the cost of copying.
📋 Instructions
**Advanced Blueprint Modification Tools** Build a program that demonstrates `ref`, `out`, `params`, and optional parameters: 1. Define `static void DoubleIt(ref int number)` — multiplies `number` by 2 in-place. 2. Define `static bool TryParseBlueprint(string input, out int result)` — uses `int.TryParse` to parse `input` into `result`, returns whether it succeeded. 3. Define `static int Sum(params int[] numbers)` — returns the sum of all numbers. 4. Define `static string Greet(string title, string name = "Architect")` — returns `"{title}, {name}!"`. 5. In `Main`: - Create `int val = 10;`, print `Original: {val}`, call `DoubleIt(ref val)`, print `After DoubleIt: {val}` - Call `TryParseBlueprint("42", out int parsed)` — if successful, print `Parsed successfully: {parsed}` - Print `Sum: ` followed by the result of `Sum(1, 2, 3, 4, 5)` - Print `Default greeting: ` followed by `Greet("Hello")`
For `ref`: declare `int val = 10;` then call `DoubleIt(ref val);`. For `out`: use `TryParseBlueprint("42", out int parsed)` with inline declaration. For `params`: just call `Sum(1, 2, 3, 4, 5)`. For optional parameters: `Greet("Hello")` uses the default `"Architect"` for the second parameter.
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.