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

ref and out Parameters

ref and out let a method work directly with your original variable instead of a copy, like lending your actual notebook instead of a photocopy. With out, the method must fill the answer in for you.

In this page:

  1. ref and out Parameters
Syntax
csharp
static void MethodName(ref type parameter)   // read and modify caller's variable
{
}

static bool TryMethod(type input, out type result)   // must assign result
{
    result = value;
    return true;
}

MethodName(ref variable);
TryMethod(input, out type result);

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);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the ref or out keyword at the call site, which is a compile error.
  2. Passing an uninitialized variable to ref, when ref needs an initialized variable and out does not.
  3. Not assigning an out parameter in every code path of the method, which is a compile error.
Chapter Summary
  • Methods group reusable code with parameters and return types.
  • Method overloading and optional parameters make methods flexible.
  • ref and out parameters pass values by reference or return extra results.
🔒

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.