390

This question already has an answer here:

What is the difference between ref and out parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?

18 답변


479

They're pretty much the same - the only difference is that a variable you pass as an out parameter doesn't need to be initialized but passing it as a ref parameter it has to be set to something.

int x;
Foo(out x); // OK

int y;
Foo(ref y); // Error: y should be initialized before calling the method

Ref parameters are for data that might be modified, out parameters are for data that's an additional output for the function (eg int.TryParse) that are already using the return value for something.


  • Also, out parameters must be set during the execution of the callee before returning to the caller, which is in opposition to ref, which must be set by the caller before calling the callee. - Jesse C. Slicer
  • @Mike Your correction is WRONG. It was right "and the method using the out parameter has to set it to something." A method receiving an out parameter has to initialize it. A method receiving a ref parameter can do to it what it wants. It can surely ignore it. I'm rollbacking it back. - xanatos
  • Surely the main difference is that ref's are in and out whereas out can only be used to return data. consider void works(ref int z) { Debug.WriteLine(z); } and void notWorks(out int z) { Debug.WriteLine(z); } or am I missing some trick to get the value of an out param before it's initialised? I notice the debugger can do it for instance. - user159335
  • So for parameters that must be set to something on the way in, ref should be used. Otherwise, use out. - FistOfFury
  • On the upside, ref can save an extra copy of a Struct from being made during a function call. On the downside, a Class could be initialized to null, so you STILL have to guard against that. - Michael Brown

124

Why does C# have both 'ref' and 'out'?

The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.

In contrast ref parameters are considered initially assigned by the caller. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.

So, out means out, while ref is for in and out.

These correspond closely to the [out] and [in,out] parameters of COM interfaces, the advantages of out parameters being that callers need not pass a pre-allocated object in cases where it is not needed by the method being called - this avoids both the cost of allocation, and any cost that might be associated with marshaling (more likely with COM, but not uncommon in .NET).


  • "In contrast ref parameters are considered initially assigned by the callee", surely you meant "caller". I tried to edit your answer but it won't let me save such a minor change. - fpsColton
  • The link has a very clear explanation of the difference, better than most answers here. Thanks! - Hannish

82

ref and out both allow the called method to modify a parameter. The difference between them is what happens before you make the call.

  • ref means that the parameter has a value on it before going into the function. The called function can read and or change the value any time. The parameter goes in, then comes out

  • out means that the parameter has no official value before going into the function. The called function must initialize it. The parameter only goes out

Here's my favorite way to look at it: ref is to pass variables by reference. out is to declare a secondary return value for the function. It's like if you could write this:

// This is not C#
public (bool, string) GetWebThing(string name, ref Buffer paramBuffer);

// This is C#
public bool GetWebThing(string name, ref Buffer paramBuffer, out string actualUrl);

Here's a more detailed list of the effects of each alternative:

Before calling the method:

ref: The caller must set the value of the parameter before passing it to the called method.

out: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.

During the call:

ref: The called method can read the argument at any time.

out: The called method must initialize the parameter before reading it.

Remoted calls:

ref: The current value is marshalled to the remote call. Extra performance cost.

out: Nothing is passed to the remote call. Faster.

Technically speaking, you could use always ref in place of out, but out allows you to be more precise about the meaning of the argument, and sometimes it can be a lot more efficient.


15

Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.

namespace outreftry
{
    class outref
    {
        static void Main(string[] args)
        {
            yyy a = new yyy(); ;

            // u can try giving int i=100 but is useless as that value is not passed into
            // the method. Only variable goes into the method and gets changed its
            // value and comes out. 
            int i; 

            a.abc(out i);

            System.Console.WriteLine(i);
        }
    }
    class yyy
    {

        public void abc(out int i)
        {

            i = 10;

        }

    }
}

Output:

10

===============================================

Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.

namespace outreftry
{
    class outref
    {
        static void Main(string[] args)
        {
            yyy a = new yyy(); ;

            int i = 0;

            a.abc(ref i);

            System.Console.WriteLine(i);
        }
    }
    class yyy
    {

        public void abc(ref int i)
        {
            System.Console.WriteLine(i);
            i = 10;

        }

    }
}

Output:

    0
    10

=================================

Hope its clear now.


9

  • A ref variable needs to be initialized before passing it in.
  • An out variable needs to be set in your function implementation
  • out parameters can be thought of as additional return variables (not input)
  • ref parameters can be thought of as both input and output variables.


9

Ref and Out Parameters:

The out and the ref parameters are used to return values in the same variable, that you pass as an argument of a method. These both parameters are very useful when your method needs to return more than one value.

You must assigned value to out parameter in calee method body, otherwise the method won't get compiled.


Ref Parameter : It has to be initialized before passing to the Method. The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.

int sampleData = 0; 
sampleMethod(ref sampleData);

Ex of Ref Parameter

public static void Main() 
{ 
 int i = 3; // Variable need to be initialized 
 sampleMethod(ref i );  
}

public static void sampleMethod(ref int sampleData) 
{ 
 sampleData++; 
} 

Out Parameter : It is not necessary to be initialized before passing to Method. The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.

 int sampleData; 
 sampleMethod(out sampleData);

Ex of Out Parameter

public static void Main() 
{ 
 int i, j; // Variable need not be initialized 
 sampleMethod(out i, out j); 
} 
public static int sampleMethod(out int sampleData1, out int sampleData2) 
{ 
 sampleData1 = 10; 
 sampleData2 = 20; 
 return 0; 
} 


6

out:

In C#, a method can return only one value. If you would like to return more than one value, you can use the out keyword. The out modifier returns as return-by-reference. The simplest answer is that the keyword “out” is used to get the value from the method.

  • You don't need to initialize the value in the calling function.
  • You must assign the value in the called function, otherwise the compiler will report an error.

ref:

In C#, when you pass a value type such as int, float, double etc. as an argument to the method parameter, it is passed by value. Therefore, if you modify the parameter value, it does not affect argument in the method call. But if you mark the parameter with “ref” keyword, it will reflect in the actual variable.

  • You need to initialize the variable before you call the function.
  • It’s not mandatory to assign any value to the ref parameter in the method. If you don’t change the value, what is the need to mark it as “ref”?


4

Ref parameters aren't required to be set in the function, whereas out parameters must be bound to a value before exiting the function. Variables passed as out may also be passed to a function without being initialized.


4

out specifies that the parameter is an output parameters, i.e. it has no value until it is explicitly set by the method.

ref specifies that the value is a reference that has a value, and whose value you can change inside the method.


1

out parameters are initialized by the method called, ref parameters are initialized before calling the method. Therefore, out parameters are used when you just need to get a secondary return value, ref parameters are used to get a value and potentially return a change to that value (secondarily to the main return value).


1

The ref keyword is used to pass values by reference. (This does not preclude the passed values being value-types or reference types). Output parameters specified with the out keyword are for returning values from a method.

One key difference in the code is that you must set the value of an output parameter within the method. This is not the case for ref parameters.

For more details look at http://www.blackwasp.co.uk/CSharpMethodParameters.aspx


1

An out parameter is a ref parameter with a special Out() attribute added. If a parameter to a C# method is declared as out, the compiler will require that the parameter be written before it can be read and before the method can return. If C# calls a method whose parameter includes an Out() attribute, the compiler will, for purposes of deciding whether to report "undefined variable" errors, pretend that the variable is written immediately before calling the method. Note that because other .net languages do not attach the same meaning to the Out() attribute, it is possible that calling a routine with an out parameter will leave the variable in question unaffected. If a variable is used as an out parameter before it is definitely assigned, the C# compiler will generate code to ensure that it gets cleared at some point before it is used, but if such a variable leaves and re-enters scope, there's no guarantee that it will be cleared again.


0

ref will probably choke on null since it presumably expects to be modifying an existing object. out expects null, since it's returning a new object.


  • Foo(ref null) won't compile, but string bar = null; Foo(ref bar); is fine. - James Curran
  • Choke on null constant? As James Curran you can't pass a constant in a ref argument. - Andrei Rînea
  • I didn't mean a null constant: I meant a variable with a null value. - Joel Coehoorn

0

out and ref are exactly the same with the exception that out variables don't have to be initialized before sending it into the abyss. I'm not that smart, I cribbed that from the MSDN library :).

To be more explicit about their use, however, the meaning of the modifier is that if you change the reference of that variable in your code, out and ref will cause your calling variable to change reference as well. In the code below, the ceo variable will be a reference to the newGuy once it returns from the call to doStuff. If it weren't for ref (or out) the reference wouldn't be changed.

private void newEmployee()
{
    Person ceo = Person.FindCEO();
    doStuff(ref ceo);
}

private void doStuff(ref Person employee)
{
    Person newGuy = new Person();
    employee = newGuy;
}


0

This The out and ref Paramerter in C# has some good examples.

The basic difference outlined is that out parameters don't need to be initialized when passed in, while ref parameters do.


0

When an out parameter is declared in the method declaration, the method body should assign a value to the out variable before returning. So it's the responsibility of the called method to assign the value to the out parameter before it returns.

When a ref parameter is declared in the method, the argument being passed while invoking the method should have assigned the value. So it's the responsibility of the caller to assign the value for the ref argument before calling the method.


0

They are subtly different.

An out parameter does not need to be initialized by the callee before being passed to the method. Therefore, any method with an out parameter

  • Cannot read the parameter before assigning a value to it
  • Must assign a value to it before returning

This is used for a method which needs to overwrite its argument regardless of its previous value.


A ref parameter must be initialized by the callee before passing it to the method. Therefore, any method with a ref parameter

  • Can inspect the value before assigning it
  • Can return the original value, untouched

This is used for a method which must (e.g.) inspect its value and validate it or normalize it.


0

out has gotten a new more succint syntax in C#7 https://docs.microsoft.com/en-us/dotnet/articles/csharp/whats-new/csharp-7#more-expression-bodied-members and even more exciting is the C#7 tuple enhancements that are a more elegant choice than using ref and out IMHO.

Linked


Related

Latest