Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ref and out in C#?

Tags:

c#

While using keyword ref, calling code needs to initialize passed arguments, but with keyword out we need not do so.

  • Why don't we use out everywhere?
  • What is exact difference between the two?
  • Please give example of a situation in which we need to use ref and can't use out?
like image 478
Pratik Deoghare Avatar asked Aug 22 '09 22:08

Pratik Deoghare


People also ask

What is difference between ref and out keyword?

Here is a list of the differences between Ref and Out Keywords in C#. We use the ref keyword when a called parameter needs to update the parameter (passed). We use the out keyword when a called method needs to update multiple parameters (passed). We use this keyword for passing data in a bi-directional manner.

What are the differences between ref and out parameters?

ref keyword is used when a called method has to update the passed parameter. out keyword is used when a called method has to update multiple parameter passed. ref keyword is used to pass data in bi-directional way.

Why do we need the out keyword?

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. Important Points: It is similar to ref keyword.


2 Answers

The answer is given in this MSDN article. From that post:

The two parameter passing modes addressed by out and ref are subtly different, however they are both very common. The subtle difference between these modes leads to some very common programming errors. These include:

  1. not assigning a value to an out parameter in all control flow paths
  2. not assigning a value to variable which is used as a ref parameter

Because the C# language assigns different definite assignment rules to these different parameter passing modes, these common coding errors are caught by the compiler as being incorrect C# code.

The crux of the decision to include both ref and out parameter passing modes was that allowing the compiler to detect these common coding errors was worth the additional complexity of having both ref and out parameter passing modes in the language.

like image 142
Vinay Sajip Avatar answered Oct 26 '22 00:10

Vinay Sajip


out is a special form of ref where the referenced memory should not be initialized before the call.

In this case the C# compiler enforces that the out variable is assigned before the method returns and that the variable is not used before it has been assigned.

Two examples where out doesn't work but ref does:

void NoOp(out int value) // value must be assigned before method returns
{
}

void Increment(out int value) // value cannot be used before it has been assigned
{
    value = value + 1;
}
like image 25
dtb Avatar answered Oct 26 '22 00:10

dtb