← Back to C# Course | Chapter 5: Methods | Lesson 6 of 6

ref and out Parameters

In this page:

  1. ref and out Parameters

ref and out Parameters

ref passes a variable by reference so the method can read and modify the caller's original value; the variable must already be initialized. out also passes by reference but is meant for methods that assign a value the method didn't receive, like TryParse. Both require the ref/out keyword at both the declaration and the call site.

Warning: An out parameter must be assigned inside the method before it returns, or the compiler rejects the code.

Example: ref and out Parameters

markup
using System;

class Program
{
    static void Double(ref int x)
    {
        x = x * 2;
    }

    static bool TryDivide(int a, int b, out int result)
    {
        if (b == 0)
        {
            result = 0;
            return false;
        }
        result = a / b;
        return true;
    }

    static void Main(string[] args)
    {
        int n = 5;
        Double(ref n);
        Console.WriteLine(n);

        if (TryDivide(10, 2, out int quotient))
            Console.WriteLine(quotient);
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.