Methods, ref/out/in Modifiers, Delegates & Action/Func Lambdas
1Concept
C# supports pass-by-reference modifiers: ref (pass by ref, read-write), out (callee must assign before return), and in (read-only reference avoiding copy of large structs). Action and Func delegates enable functional programming.
2Architecture Diagram
ref T : Pass address, variable must be initialized by caller out T : Pass address, variable MUST be initialized by callee in T : Pass address, read-only (zero copy overhead)
3Code Example
Stage 0 Language Foundations
using System;
class Program
{
static bool TryParseInteger(string input, out int result)
{
return int.TryParse(input, out result);
}
static void Main()
{
// Out parameter
if (TryParseInteger("4500", out int parsedVal))
{
Console.WriteLine($"Successfully parsed integer: {parsedVal}");
}
// Func & Action Lambdas
Func<int, int, int> multiply = (a, b) => a * b;
Action<string> logMessage = msg => Console.WriteLine($"[LOG] {msg}");
logMessage($"Result: {multiply(8, 9)}");
}
}4Expected Output
Successfully parsed integer: 4500 [LOG] Result: 72
5Key Takeaways
- ✓Use out parameters for TryParse patterns returning status boolean and value.
- ✓Use in modifiers for large readonly structs (in Vector3D) to avoid copy overhead.
- ✓Func<T1, T2, TResult> has a return value; Action<T> returns void.