Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 182 ยท Methods

Parameters: ref, out, in and params

Master C# parameter passing - by value vs by reference, ref, out variables and discards, in and ref readonly, params arrays and params collections (C# 13), plus ref returns and ref locals.

By default, C# passes arguments by value: the method gets a copy. That default is right most of the time, but it can't express some perfectly reasonable ideas: "swap these two variables", "tell me whether the parse worked and give me the number", "don't copy this 64-byte struct for every call", "accept any number of arguments". For those jobs C# adds four parameter modifiers: ref, out, in and params.

This lesson explains each modifier by what happens in memory, shows the idiomatic uses (the TryParse pattern above all), and ends with ref returns and ref locals, which hand out references to storage rather than copies. It continues from Methods and builds on Value Types and Reference Types.

Pass by value, once more

Before the modifiers, be precise about the default. Passing an argument by value copies the value of the variable:

  • For a value type (int, double, bool, struct), the whole value is copied. The method can't touch the caller's variable.
  • For a reference type (class, array, string), the reference is copied. The method and the caller hold two variables that point to the same object. Changing the object's contents is visible to both; assigning a different object to the parameter is not.

Everything below changes one thing: the parameter becomes an alias for the caller's variable, not a copy.

ref: read and write the caller's variable

A ref parameter doesn't get a copy: it is the caller's variable under another name. You must write ref both in the method declaration and at the call site, which makes the intent visible to the reader. The variable must already have a value before the call.

C# ref parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last example shows the second use of ref: letting a method replace the object a caller's variable points to. Without ref, Array.Resize couldn't give you a bigger array, only fill the one you passed in.

Use ref sparingly. A method that changes its arguments is harder to reason about than one that takes inputs and returns a result. Reach for ref for performance-sensitive code and for APIs where the method truly must update a variable in place, like Interlocked.Increment(ref count).

out: a method that returns more than one thing

An out parameter is like ref for output only. The caller doesn't need to initialize the variable, and the method must assign it before returning normally. The compiler enforces this, so an out value can never be garbage.

The classic use is the Try pattern: return a bool for success, deliver the result through an out. It avoids exceptions for expected failures, such as bad user input. int.TryParse, Dictionary.TryGetValue and Guid.TryParse all work this way.

C# out variables and the Try pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If a method forgets to assign an out parameter on some path, it doesn't compile:

C# Forgetting to assign an out parameter (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS0177: The out parameter 'half' must be assigned to before control leaves the current method. Assign half = 0; before returning false.

Tuples are often nicer than out

When the method always returns several values, a tuple (covered in Tuples and Deconstruction) reads better than several out parameters: (int quotient, int remainder) DivRem(int a, int b). Keep out for the Try pattern and for places where the return value is already taken.

in: pass by reference, read-only

An in parameter is passed by reference but cannot be modified. Its purpose is speed: a large struct copied on every call is wasteful, and in passes only a small reference. At the call site in is optional (the compiler adds it); you may write it to be explicit.

C# in parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two rules make in pay off:

  1. Use it only for large structs (roughly more than 16 bytes). Passing an int by in is slower than copying it, because of the extra indirection.
  2. Make the struct readonly. If the struct is mutable, the compiler must defensively copy it before calling its methods (so a method can't change it through the reference), which cancels the saving.

Assigning to an in parameter is an error:

C# Assigning to an in parameter (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The message is error CS8331: Cannot assign to variable 'p' or use it as the right hand side of a ref assignment because it is a readonly variable.

ref readonly (C# 12)

C# 12 added ref readonly parameters. They are like in, but the caller must pass an actual variable with ref (or in), and passing a literal or a temporary gives a warning. That lets an API author insist on "a real, long-lived variable" for APIs that hold on to the reference. Prefer in unless you need that stricter rule.

C# ref readonly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

params: any number of arguments

A params parameter lets callers pass a comma-separated list instead of building a collection. It must be the last parameter, and a method can have only one. string.Join, Path.Combine and Console.WriteLine(string, params object[]) use it.

Until C# 12, params required an array. C# 13 (.NET 9) allows params with other collection types: Span<T>, ReadOnlySpan<T>, IEnumerable<T>, List<T> and any type that supports collection expressions. The span versions are the interesting ones: the compiler can put the arguments on the stack, so the call allocates nothing.

C# params arrays and params collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Pitfalls worth knowing:

  • A params object[] and a single array argument can confuse callers: Describe("x", someStringArray) passes the array as the whole values (an array of strings is also an object[] through array covariance), whereas Describe("x", (object)someStringArray) makes it a single element.
  • Each call to a params T[] method allocates a new array. In hot code, prefer the ReadOnlySpan<T> form on .NET 9 and later, or provide fixed-arity overloads (the .NET libraries do both).
  • Overload resolution prefers a method with a normal (non-params) parameter list when it fits, so adding Sum(int a, int b) next to Sum(params int[] n) makes two-argument calls use the fixed version.

ref returns and ref locals

A method can also return a reference to a variable instead of a copy of its value. The declaration puts ref before the return type, the return statement says return ref ..., and the caller can store the result in a ref local (ref int slot = ref ...) which is an alias to the original storage. Writing through the alias changes the original, such as an array element.

C# ref returns and ref locals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler only allows a ref return when the referenced storage outlives the method: an array element, a field of an object, a static field, or another ref parameter. Returning a reference to a local variable would leave a dangling pointer, so it is a compile error (CS8168). This is the safety net that makes ref returns acceptable in a memory-safe language.

You will see ref returns inside Span<T> indexers, CollectionsMarshal.GetValueRefOrNullRef and other performance APIs; in everyday application code you rarely write them.

Choosing a modifier

You want to... Use
just give the method some input nothing (by value)
change the caller's variable ref
return an extra result, especially TryXxx out
avoid copying a large readonly struct in
accept a variable number of arguments params
expose a variable's storage to the caller ref return

Reading the modifiers in a call (Swap(ref a, ref b), TryParse(s, out var n)) tells the reader exactly where data can flow. That visibility is a feature: if a call has no keyword, no argument variable can change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must a method do with an out parameter?

    The compiler requires every normal exit to assign the out parameter (error CS0177 otherwise), and the caller doesn't need to initialize it first.
  2. 2. What does int.TryParse("abc", out int n) return, and what is n?

    TryParse returns false for bad text and sets the out parameter to default(int), which is 0. It never throws for bad input.
  3. 3. Which struct design makes in parameters pay off?

    in avoids copying big structs. If the struct is not readonly, the compiler makes defensive copies, and for tiny types the extra indirection costs more than the copy.
  4. 4. Which signature is valid in C# 13?

    params must be the last parameter, there can be only one, and since C# 13 it can be a span or other collection type, not just an array.
  5. 5. What does ref int top = ref Largest(scores); top = 100; do?

    A ref local is an alias for the element the ref-returning method pointed at, so writing to it changes the array itself.

Summary

  • By default, arguments are copied. Reference types copy the reference, so the object is shared.
  • ref aliases the caller's variable (initialized before the call). out is output-only and must be assigned before the method returns. Both need the keyword at the call site.
  • out var x, out int x and discards (out _) make TryXxx calls concise. Prefer the Try pattern over exceptions for expected failures.
  • in passes large readonly structs by reference without allowing writes; ref readonly (C# 12) additionally demands a real variable.
  • params takes a variable number of arguments. It must be last. C# 13 extends it from arrays to spans and other collection types.
  • A ref return plus a ref local give you an alias to existing storage, for in-place edits and performance code.

Next: Optional and Named Arguments