Parameters by value and by reference

 

1 - Parameters by value

When we pass a parameter to a method, we are not actually sending the parameter itself, we are 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 still equals 10 after finishing the Actualizar() method because the value is only modified inside that method.

 

 

2 - Parameters by reference

There may be times when we need to update the value of the data. For this, we use parameters by reference, which we do by using the reserved words ref and out. When we use ref and out, we do not store the value of the variable, but its memory address. So, if we modify the value, we also change the original variable.

 

2.1 - Reserved word ref

Using ref means that you will pass the value by reference to a method, which implies that the value will change inside the method. Moreover, if you want to use ref, the variable has to be initialized beforehand.

Finally, you must indicate in both the method and the method call that you are passing a value by reference.

static void Main(string[] args)
{
    int valorActual = 10;

    ActualizarRef(ref valorActual); //pasar por referencia
    Console.WriteLine($"el valor es: {valorActual}"); // imprime 12

  
    Console.ReadKey();
}

//Actualizar por referencia
public static void ActualizarRef(ref int valor)
{
    valor += 2;
}

 

2.2 - Reserved word out

Using outmeans that the assignment of the value to that variable takes place inside the method being called. It is not necessary to initialize the value of the variable, although you 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();
}


//Crear utilizando out
public static void ActualizarOut(out int valor)
{
    valor = 13;
}

 

2.3 - Reserved word In

The in keyword prevents you from modifying the value of the variable within the method, so the value will always be the one you initially passed.

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 inside a function, it will be updated outside 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 value of the variable, on the other hand, if we want to create a new variable we must use out. Use in when you want the value to not be modifiable.
  • We cannot use in, ref, or out in asynchronous methods or iterators.

 

5 - When to use ref or out?

We use refor out when we need multiple return values from a single method.

Since the arrival of .NetFramework 4.0 it is 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

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

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

Buy me a coffee Invitame a un café