C# Functions & References
ref, out, in, params) plus lambdas and local functions for functional style.
Methods
Signature
A method declares an access modifier, return type, name, and parameter list. static means it belongs to the type, not an instance.
static int Add(int a, int b)
{
return a + b;
}
Overloading
Overloads share a name but differ in parameter types or count. The return type alone cannot distinguish overloads.
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
Parameters
ref
ref passes a reference to the caller's variable. The method may read and change it; the caller must initialize it first.
static void Double(ref int value) => value *= 2;
int n = 5;
Double(ref n);
Console.WriteLine(n); // 10
out
out returns extra values. The method must assign it before returning; the caller may pass an uninitialized variable.
static void Split(string name, out string first, out string last)
{
string[] parts = name.Split(' ');
first = parts[0];
last = parts[1];
}
Split("Ada Lovelace", out string f, out string l);
Console.WriteLine(f); // Ada
in
in passes a readonly reference; no copy is made and the method cannot modify it.
static double Distance(in Point p)
=> Math.Sqrt(p.X * p.X + p.Y * p.Y);
params
params accepts a variable number of arguments as an array.
static int Sum(params int[] values)
{
int total = 0;
foreach (int v in values) total += v;
return total;
}
Console.WriteLine(Sum(1, 2, 3)); // 6
Optional & Named
Optional parameters have a default value; named arguments let you pass by name in any order.
static void Greet(string name, string greeting = "Hello")
=> Console.WriteLine($"{greeting}, {name}!");
Greet("Ada"); // Hello, Ada!
Greet(name: "Ada", greeting: "Hi"); // Hi, Ada!
Lambdas & Local Functions
Lambda Expressions
A lambda is an anonymous function. Func<T, TResult> is the standard delegate type.
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // 25
Local Functions
Local functions are named helpers declared inside a method, so they only work in that scope.
static int Compute(int a, int b)
{
int Add(int x, int y) => x + y; // local function
return Add(a, b);
}