Parameters by Value and by Reference

 

1 - Parameters by value

When we pass a parameter to a method, we're not actually sending that parameter, we're sending a copy of it. This means that outside the method, the value of the variable will remain the same, even if we modify it internally.

static void Main(string[] args){    int valorActual = 10;    Actualizar(valorActual);     Console.WriteLine($"el valor es: {valorActual}");//imprime 10    Console.ReadKey();}//Comportamiento normal.public static void Actualizar(int valor){    valor += 5;    Console.WriteLine($"el valor es: {valor}"); //imprime 15}

valorActual remains 10 after the Actualizar() method ends, since the value is only modified within that method.

 

 

2 - Parameters by reference

There may come a time when we need to update the value of data. To do this, we'll pass parameters by reference, using the reserved words ref and out. When we use ref and out, we don't store the value in the variable, but the memory position it points to, so if we modify the value, we also change the original one. 

 

2.1 - Reserved word ref

Using ref means you will pass the value by reference to a method, so the value may change inside the method. Also, if you want to use ref, the variable has to have been initialized beforehand.

Finally, we must specify in both the method definition and the method call that we are passing a value by reference.

static void Main(string[] args){    int valorActual = 10;    ActualizarRef(ref valorActual); //pass by reference    Console.WriteLine($"el valor es: {valorActual}"); // imprime 12      Console.ReadKey();}//Update by referencepublic static void ActualizarRef(ref int valor){    valor += 2;}

 

2.2 - Reserved word out

Using out means the value of that variable is assigned inside the method being called. It's not necessary to initialize the variable's value, though we do need to declare it.

static void Main(string[] args){    int valorActual;    ActualizarOut(out valorActual);    Console.WriteLine($"el valor es: {valorActual}"); // imprime 13    Console.ReadKey();}//Create using outpublic static void ActualizarOut(out int valor){    valor = 13;}

 

2.3 - Reserved word In

The in keyword prevents us from modifying the variable's value inside the method, so the value will always be the one we passed in.

public static void ActualizarIn(in int valor){    valor += 5; //Da Error     Console.WriteLine($"el valor es: {valor}");}

 

 

3 - The special case of objects

When we pass an Object/Type created by ourselves, it is always passed by reference. So if we update it within the function, it will be updated outside of it as well.

class Program{    static void Main(string[] args)    {                ObjEjemplo ejemploValor = new ObjEjemplo(10);        ActualizarObj(ejemploValor);        Console.WriteLine($"el valor es: {ejemploValor.Entero}"); // imprime 25        Console.ReadKey();    }    public static void ActualizarObj(ObjEjemplo obj)    {        obj.Entero = 25;    }}public class ObjEjemplo{    public int Entero { get; set; }    public ObjEjemplo(int entero)    {        Entero = entero;    }}

 

 

4 - Final notes

  • We should use ref if we want to change the variable's value. If we want to create a new variable, we should use out. Use in when we don't want the value to be modified.
  • We cannot use in, ref, or out in asynchronous methods or iterators. 

 

5 - When to use ref or out?

We use ref or out when we need multiple return values from the same method.

Since the advent of .NetFramework 4.0 it's more common to use Tuple<T> when we need more than one output value.

 

 

6 - Code

The code is available on GitHub here

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café