Ref and out parameters let a method change the value of variables you pass in. This helps when you want to get more than one result from a method.
0
0
Ref and out parameters in C Sharp (C#)
Introduction
When you want a method to update a variable you pass in.
When you want to return multiple values from a method without using a special object.
When you want to avoid copying large data by passing a reference instead.
When you want to make sure a variable is assigned inside a method before using it.
When you want to share data changes between methods easily.
Syntax
C Sharp (C#)
void MethodName(ref int number) { /* code */ } void MethodName(out int number) { /* code */ }
ref requires the variable to be initialized before passing.
out requires the method to assign a value before it ends.
Examples
This method adds one to the number passed by reference.
C Sharp (C#)
void AddOne(ref int number) { number = number + 1; }
This method sets the number to 10 using an out parameter.
C Sharp (C#)
void Initialize(out int number) { number = 10; }
Shows how to call a method with a ref parameter.
C Sharp (C#)
int value = 5; AddOne(ref value); // value is now 6
Shows how to call a method with an out parameter.
C Sharp (C#)
int result; Initialize(out result); // result is now 10
Sample Program
This program shows how to use ref to change a variable and out to get multiple values from a method.
C Sharp (C#)
using System; class Program { static void AddFive(ref int number) { number += 5; } static void GetValues(out int a, out int b) { a = 3; b = 7; } static void Main() { int x = 10; AddFive(ref x); Console.WriteLine($"After AddFive, x = {x}"); int val1, val2; GetValues(out val1, out val2); Console.WriteLine($"Values from GetValues: {val1} and {val2}"); } }
OutputSuccess
Important Notes
You must use the ref or out keyword both when declaring the method and when calling it.
Variables passed with ref must be initialized before the call.
Variables passed with out do not need to be initialized before the call, but the method must assign them before it ends.
Summary
ref lets a method read and change a variable you already set.
out lets a method give back values by assigning variables inside it.
Use these to share data between methods without returning complex objects.