What are the out and ref parameters

Asked

Viewed 16,435 times

28

What is the use of parameter types ref and out of a method in C#? What is the difference between the two? Some example of each one’s use.

  • Answers to questions like this are in the documentation. If, after reading the documentation, you have any specific questions, ask here.

  • 3

    I read the documentation, but now with the answers here it became much clearer to min.

2 answers

33


Simply a normal parameter has a sense, it only goes, the argument value is only sent to the parameter. O out also has only one sense, but otherwise, it only passes the value of the parameter (what is inside the method) to the argument. The ref do both. It sends an argument value to the parameter and returns the value of the parameter for the argument.

Both argument and parameter must contain the modifier.

ref

The ref is to pass the argument by reference, that is, instead of passing its value, a pointer is passed that indicates where the value is. This way when the parameter has changed its value, it will be changing the argument value since they are in the same memory position.

Its use only makes sense if the argument has a value. In general the parameter must be changed within the parameter, at least this must happen conditionally.

In the background a parameter by reference is an alias for an existing variable in another context.

class RefExample {
    static void Method(ref int i) {
        i = i + 44;
    }
    static void Main() {
        int val = 1;
        Method(ref val);
        Console.WriteLine(val);
        // Output: 45
    }
}

I put in the Github for future reference.

out

The out indicates that the argument to be passed will receive a value within the method. That is, it is a reference too, but no value is passed to the parameter, it is just a way to output a value. This is usually necessary because the return can only have one value.

Using it the argument does not need to have a value but the parameter needs to receive a value before terminating the method execution.

It is faster in some scenarios.

It is true that it is possible to return a Tuple stop "group" several values. But it is not very elegant. Some however, prefer so.

Added the return of multiple values in C# 7. Can do this: public (bool, int) Metodo(string).

class OutExample {
    static void Method(out int i) {
        i = 44;
    }
    static void Main() {
        int value;
        Method(out value);
        // value is now 44
    }
}

I put in the Github for future reference.

The TryParse() is one of the best use examples. It returns a boolean indicated if the parse was successful and in the parameter out returns the numeric value obtained, if possible. If it is not possible, nothing is returned in it and cannot be used.

in

In C# 7.2 there is the in which allows a parameter to be received as a reference equal to ref, but it is guaranteed that this value will not be changed, at least by the reference (if you try to modify it will use a technique of COW). It is useful in cases that require a lot of performance and do not want to make an allocation on heap by pressing GC. Think of it as a ref readonly.

Completion

C# now has the feature of multiple returns, the out is no longer needed in most cases. And the ref is a way of passing data by value as references. The internal mechanism of out is equal to that of the ref but the compiler can optimize the code and avoid passing the value.

Note which types are by reference (a List, for example, or any type created with class), are already passed as if it were ref (simply speaking, the mechanism of how it is treated is a little different internally).

It is necessary to be careful with the use of ref in competitive scenarios.

If you want a detailed explanation you have a excellent article by Jon Skeet.

  • Roughly, could you compare them to pointers then? But with some refinement as to how to use, that’s it?

  • 1

    @bruno101 yes, because internally they are pointers, there is only one cover that makes it easy to understand and provides useful restrictions for your best use.

  • @Maniero from which version the multiple return is present in C# ?

  • @Jeanextreme002 does not remember well, 7 and something, I usually treat as 7, even if it is not 0.

  • @Maniero How so 7 if the latest version was the 4.8 ? Could be clearer ?

  • The latest version is 8, and is about to release 9. Read https://answall.com/q/21672/101.

Show 1 more comment

9

Parameters ref are changed in the call location. They are passed as references, not values. This means that you can assign the parameter in the called method and have it also be assigned in the call location.

The keyword out force the arguments to be passed by reference. This is like the reference keyword, except that ref requires the variable to be initialized before it is passed. To use an out parameter, the method definition and method call must explicitly use the out keyword. For example:

Out

Follow the examples:

static void Main()
{
    string value1 = "gato"; 
    SetString1(ref value1); //Passando value1 como referência
    Console.WriteLine(value1); 

    string value2; // String sem atribuição
    SetString2(1, out value2); // Passando value2 como out
    Console.WriteLine(value2); 
    }

    static void SetString1(ref string value)
    {
    if (value == "gato")
    {
        Console.WriteLine("É gato");
    }
        value = "cachorro"; // Atribui novo valor ao parametro
    }

    static void SetString2(int number, out string value)
    {
    if (number == 1) 
    {
        value = "um"; // Atribui o parametro out
    }
    else
    {
        value = "outro valor"; // Atribui o parametro out 
    }
}

Exits:

Is cat

dog

one

References:

http://www.dotnetperls.com/ref

https://msdn.microsoft.com/pt-br/library/ee332485.aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.