Home c# how does OUT differ from ref?

how does OUT differ from ref?

Author

Date

Category

The function with a key word Out gives the same result as with Ref .

Such code:

Private Void Func (Out String Value)
{
  Value = "Hello World!";
}

gives the same effect as and

Private void Func (Ref String Value)
{
  Value = "Hello World!";
}

What is the difference between Out and Ref ?


Answer 1, Authority 100%

The difference is that Out is the output parameter, and Ref – input and output.

For Ref -prameter you must transfer it to initialized, and you can use it source value. And for OUT -Prameter, you are not required to initialize it before calling the function, you cannot use its value to the function before assigning, and must initialize it in the function.

(Thus, Ref Parameter reminds a little reminds Initialized Local variable, and Out -prameter – Uninitialized .)

illustration:

Private void Func1 (Out String Value)
{
  Console.WriteLine (Value); // Can not, Value is not initialized
  if (false)
    Return; // You can not, forgot to set the value of Value
  Value = "Hello World!";
}
String S1;
FUNC1 (OUT S1);
Private void Func2 (Ref String Value)
{
  Console.WriteLine (Value); // can
  if (false)
    Return; // Not a problem, Value remains an old value
  Value = "Hello World!";
}
String S2;
FUNC2 (REF S2); // it is impossible, the function has the right to use the value,
        // So, it must be initialized first

Thus, Out -prameter is like an additional returned function value. A ref is a parameter – a parameter whose change is visible outside the function

.


On the CLR level to out – and ref -parameters uses the same mechanism, but this is a minor technical details. The difference in semantics.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions