Parameters: Ref, Out, and In

Parameters: Ref, Out, and In in C#: When you hand a document to a colleague you have four choices, and C# has exactly the same four.

The Analogy: The Photocopy, the Original, and the Blank Form

When you hand a document to a colleague you have four choices, and C# has exactly the same four.

You can give them a photocopy. They can scribble on it all they like and your original is untouched — that is a normal parameter, passed by value.

You can hand over the original file. Anything they write is written on your copy, because there is only one. That is ref.

You can give them a blank form to fill in and require it back completed. That is out: you are not passing information in, you are asking for information out, and the method is not allowed to hand the form back empty.

Or you can show them the document behind glass — no copy made, but no writing allowed either. That is in, which exists so that a large struct can be passed without being duplicated.

The one place this analogy needs care is when the document is itself an address rather than a page, which is what happens with every class and array. That case gets its own section below, because it is where the real confusion lives.


Syntax or Core Structure

using System;

class Program
{
    struct Point { public double X, Y; }

    static void Bump(int n)        { n += 10; }              // copy
    static void BumpRef(ref int n) { n += 10; }              // the original

    static void Split(string text, out string head, out string tail)
    {
        int i = text.IndexOf(' ');
        head = i < 0 ? text : text[..i];
        tail = i < 0 ? "" : text[(i + 1)..];
    }

    static double Length(in Point p) => Math.Sqrt(p.X * p.X + p.Y * p.Y);

    static void Fill(int[] data)           { data[0] = 99; }
    static void Replace(int[] data)        { data = new[] { 7 }; }
    static void ReplaceRef(ref int[] data) { data = new[] { 7 }; }

    static void Main()
    {
        int a = 1;
        Bump(a);
        Console.WriteLine($"after Bump: {a}");
        BumpRef(ref a);
        Console.WriteLine($"after BumpRef: {a}");

        Split("hello world again", out string head, out string tail);
        Console.WriteLine($"head '{head}' tail '{tail}'");

        var p = new Point { X = 3, Y = 4 };
        Console.WriteLine($"length {Length(in p)}");

        int[] xs = { 1, 2, 3 };
        Fill(xs);
        Console.WriteLine($"after Fill: {string.Join(",", xs)}");
        Replace(xs);
        Console.WriteLine($"after Replace: {string.Join(",", xs)}");
        ReplaceRef(ref xs);
        Console.WriteLine($"after ReplaceRef: {string.Join(",", xs)}");
    }
}

Output:

after Bump: 1
after BumpRef: 11
head 'hello' tail 'world again'
length 5
after Fill: 99,2,3
after Replace: 99,2,3
after ReplaceRef: 7

The last three lines are the whole lesson in miniature. Fill mutated the array both names point at, so the caller sees 99. Replace rebound its own copy of the reference to a new array, so the caller sees nothing — the change died with the parameter. ReplaceRef was handed the caller's variable itself, so rebinding it took effect.


Technical Depth: Four Modifiers and One Two-by-Two Table

The four passing modes differ in three things: which direction data flows, what the caller must do before the call, and what the method must do before it returns.

ModeDirectionCaller must initialise firstMethod must assign before returningCall site keyword
(none)in, by copyyesnonone
refin and outyesnoref
outout onlynoyes, on every pathout
inin, by referenceyesno, assignment is forbiddenoptional in

C# requires ref and out at the call site as well as the declaration. That is deliberate: reading Save(ref total) tells you total may come back changed without having to open Save.

Now the two-by-two that trips up everyone who came from Java or Python. There are two independent questions — is the type a value type or a reference type, and is the parameter by value or by ref?

passed by value (default)passed with ref
value type (int, struct)method gets its own copy of the data; caller sees nothingmethod shares the caller's storage; every write is visible
reference type (class, array)method gets its own copy of the address; mutations are visible, reassignment is notmethod shares the caller's variable; reassignment is visible too

The bottom-left cell is the famous one. "Objects are passed by reference" is a half-truth: the object is shared, but the variable holding it is not. Replace above proves it.

out and the Try pattern

out exists mainly so a method can return a result and a success flag without throwing. You can declare the variable inline, and discard the ones you do not want:

if (int.TryParse(text, out int n))
    Console.WriteLine(n * 2);

if (dict.TryGetValue("key", out _))     // "is it there?" and nothing else
    Console.WriteLine("present");

Every out parameter must be assigned on every return path, including the error paths, or the compiler raises CS0177. The habit that makes this painless is to assign defaults on the first two lines of the method:

static bool TryLoad(string path, out Config config, out string error)
{
    config = default;      // now every early return below is legal
    error = "";
    ...
}

in, and the hidden copy that undoes it

in means "pass by reference, but read-only". Its purpose is performance: a 64-byte struct passed by value is 64 bytes copied on every call, and in passes an address instead.

There is a trap. If the struct is not declared readonly, the compiler cannot prove that calling a member on it will not mutate it, so it makes a defensive copy before every single member access — turning one copy per call into several. Declaring the struct readonly removes them:

readonly struct Vector          // readonly: no defensive copies at all
{
    public readonly double X, Y;
    public Vector(double x, double y) { X = x; Y = y; }
    public double Magnitude => Math.Sqrt(X * X + Y * Y);
}

static double Sum(in Vector a, in Vector b) => a.Magnitude + b.Magnitude;

So the rule is: in only pays for itself on large readonly structs. On an int it is pure overhead, because a reference is as big as the value it points to.

ref returns and ref locals

A method can hand back a reference to storage rather than a copy of it, which lets the caller write through it:

static ref int Largest(int[] xs)
{
    int best = 0;
    for (int i = 1; i < xs.Length; i++)
        if (xs[i] > xs[best]) best = i;
    return ref xs[best];
}

int[] scores = { 3, 9, 4 };
ref int top = ref Largest(scores);
top = 0;                                   // writes into scores[1]
Console.WriteLine(string.Join(",", scores));   // 3,0,4

You may only ref-return storage that outlives the method — an array element or a field, never a local. This is the machinery behind Span<T> and the ref struct types, which is where it earns its keep; in ordinary application code it is rare.

params, optional, and named arguments

params is the opposite end of the spectrum: not one argument passed carefully, but any number passed loosely.

static int Total(params int[] values)
{
    int sum = 0;
    foreach (int v in values) sum += v;
    return sum;
}

Total();              // 0   - an empty array, not null
Total(1, 2, 3);       // 6
Total(new[] { 4, 5 }); // 9  - you may still pass the array directly

params must be last, there can be only one, and it cannot be combined with ref, out or in. Named arguments let you skip past optional parameters and, more usefully, label the ones that would otherwise be a row of anonymous true/false:

Export(path, overwrite: true, includeHeaders: false);

Where these modifiers are not allowed

ref, out and in are banned in async methods and in iterators (yield return), because both of those are rewritten into state machines whose frames outlive the call. When you need several results out of an async method, return a tuple or a small record instead:

static async Task<(bool ok, string error)> TrySendAsync(string url) { ... }

That tuple-returning shape is worth reaching for in synchronous code too. Two out parameters read fine; four is a signature nobody wants to call.


Real World Example: A Sensor Import That Never Throws

Import code is the natural home of out. Each line either parses or it does not, and a bad line is normal input rather than an exceptional event — so the parser returns a bool and hands back both the parsed record and the reason for failure through out. A tiny ref helper then accumulates the running totals in place.

using System;
using System.Globalization;

readonly record struct Reading(string Sensor, double Value, DateTime TakenAt);

class Program
{
    static bool TryParseReading(string line, out Reading reading, out string error)
    {
        reading = default;                 // assign both up front, so every
        error = "";                        // early return below is legal

        string[] parts = line.Split(',');
        if (parts.Length != 3)
        {
            error = $"expected 3 fields, got {parts.Length}";
            return false;
        }

        if (!double.TryParse(parts[1], NumberStyles.Float,
                             CultureInfo.InvariantCulture, out double value))
        {
            error = $"bad value '{parts[1]}'";
            return false;
        }

        if (!DateTime.TryParseExact(parts[2], "yyyy-MM-dd",
                                    CultureInfo.InvariantCulture,
                                    DateTimeStyles.None, out DateTime taken))
        {
            error = $"bad date '{parts[2]}'";
            return false;
        }

        reading = new Reading(parts[0], value, taken);
        return true;
    }

    static void Accumulate(ref double sum, ref int count, double value)
    {
        sum += value;
        count++;
    }

    static void Main()
    {
        string[] lines =
        {
            "boiler-3,71.5,2026-03-01",
            "boiler-3,warm,2026-03-02",
            "boiler-4,68.5,2026-03-03",
            "boiler-4,70.0,03/03/2026",
            "boiler-5,72.75",
        };

        double sum = 0;
        int count = 0;

        foreach (string line in lines)
        {
            if (TryParseReading(line, out Reading r, out string error))
            {
                Accumulate(ref sum, ref count, r.Value);
                Console.WriteLine($"ok   {r.Sensor,-9}{r.Value,7:F2}  {r.TakenAt:yyyy-MM-dd}");
            }
            else
            {
                Console.WriteLine($"skip {line,-26}({error})");
            }
        }

        Console.WriteLine($"accepted {count}, mean {(count == 0 ? 0 : sum / count):F2}");
    }
}

Output:

ok   boiler-3   71.50  2026-03-01
skip boiler-3,warm,2026-03-02  (bad value 'warm')
ok   boiler-4   68.50  2026-03-03
skip boiler-4,70.0,03/03/2026  (bad date '03/03/2026')
skip boiler-5,72.75            (expected 3 fields, got 2)
accepted 2, mean 70.00

Three details are worth pulling out. reading and error are assigned on the first two lines, which is what makes the three early return false statements compile. out Reading r is declared inline at the call site, so r exists only where it is meaningful. And the third field of line four is a real date in a real format — just not this format — which is exactly why TryParseExact with InvariantCulture is the right tool: the same file must import identically on a machine whose locale reads dates day-first.

The two-out signature is at its comfortable limit here. Had a third result been needed, the honest move would have been a return type of (bool ok, Reading reading, string error), or a small ParseResult record.


Common Mistakes

  1. Expecting a plain int or struct argument to come back changed. Without ref, the method only ever touched a copy — the caller's variable is untouched.
  2. Believing that because a class was passed, the method can hand back a different object. Reassigning the parameter rebinds only the method's own copy of the reference; you need ref for the caller to see a new object.
  3. Omitting ref or out at the call site. C# requires the keyword in both places; Split(text, head, tail) will not compile.
  4. Passing an unassigned local as ref. ref promises data flows in as well as out, so the variable must be initialised first — that is what out is for when it is not.
  5. Forgetting to assign an out parameter on an error path, producing CS0177. Assign defaults at the top of the method and the problem disappears.
  6. Reaching for out inside an async method or an iterator. Neither permits it; return a tuple or a record instead.
  7. Using in on a struct that is not declared readonly, which makes the compiler insert defensive copies and leaves the code slower than plain by-value passing.
  8. Growing a signature to three or four out parameters. Past two results, a tuple or a named record is easier to read and impossible to pass in the wrong order.

Best Practices

  • Pass by value by default. Reach for a modifier only when you can name the reason.
  • Reserve out for the Try pattern — a bool return plus the value — and name such methods TryX.
  • Declare out variables inline (out int n) and discard the ones you ignore (out _).
  • Return a tuple or a small record when a method genuinely produces several values; keep out to one or two.
  • Use ref only where mutating the caller's storage is the point, such as an in-place accumulator or a hot-path struct.
  • Make a struct readonly before passing it with in, and only bother with in once the struct is genuinely large.
  • Use named arguments at call sites that would otherwise be a row of unlabelled booleans.
  • Document, in a /// comment, whether a method mutates a collection it was handed. The signature cannot express it, so the comment must.

Practice Exercises

  1. Write static void Swap(ref int a, ref int b) and prove it works from Main. Then write a second version without ref and print both results side by side to show which one changed the caller's variables.
  2. Implement static bool TryDivide(int numerator, int denominator, out int quotient, out int remainder) that returns false for a zero denominator. Assign both out parameters on every path, then call it in a loop over the pairs (17, 5), (9, 0) and (-7, 2) and print each outcome.
  3. Write static void MinMax(int[] xs, out int min, out int max) and a second method static (int min, int max) MinMaxTuple(int[] xs) that returns the same information as a tuple. Call both and write two sentences on which call site you find easier to read.
  4. Create readonly struct Box with three double fields and a Volume property, plus static double TotalVolume(in Box a, in Box b). Then write static void Grow(int[] sizes) that both mutates sizes[0] and reassigns sizes to a new array, call it, and print the caller's array to demonstrate that only the mutation survived.