CodeBlanks Logo Icon CodeBlanks

ref parameters

C# course · Beginner · Lesson 80/116

Learn pass-by-reference with ref and how changes propagate to the caller.

ref parameters

The ref keyword passes a variable by reference. Changes made inside the method are visible to the caller. In normal passing the value is copied; with ref the variable itself is shared.

The ref keyword appears in both the declaration and the call: static void Double(ref int n) and Double(ref x). A variable passed with ref must be initialized before the call.

Using ref

The ref keyword must appear in both the declaration and the call. Writing it in only one place gives a compile error. The variable must be initialized before the call; otherwise ref cannot be used.

ref is especially useful for value types (int, double, struct) because these normally pass by value copy. It is used to return multiple values or to modify a value inside a method.

Exercise Triple method

Define a static void Triple(ref int n) method; in the body write n = n * 3;. In Main, call int x = 7; Triple(ref x); and print x with Console.WriteLine.

Show example solution
Add n = n * 3; to the Triple body, write int x = 7; Triple(ref x); Console.WriteLine(x); in Main.
Example solution:
using System;

class Program
{
    static void Triple(ref int n)
    {
        // Triple n
        n = n * 3;
    }

    static void Main()
    {
        // Declare x, modify with Triple and print
        int x = 7;
        Triple(ref x);
        Console.WriteLine(x);
    }
}

Test yourself

  1. What does Console print after Double(ref x)?

    static void Double(ref int n)
    {
        n = n * 2;
    }
    int x = 5;
    Double(ref x);
    Console.WriteLine(x);
    • 5
    • 0
    • 10
    • 20
    Show answer

    10 — Correct. With ref, x itself was changed; x = 10.

  2. Match each expression to its meaning

    ref int n
    By reference
    Double(ref x)
    ref at call
    int x = 5;
    Initialize first
    n = n * 2;
    Change reflects
  3. ref call

    int x = 4;
    Double(____);
    Console.WriteLine(x);
    Show answer
    int x = 4;
    Double(ref x);
    Console.WriteLine(x);

All lessons in Beginner