While using keyword ref
, calling code needs to initialize passed arguments, but with keyword out
we need not do so.
out
everywhere?ref
and can't use out
?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.
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.
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.
The answer is given in this MSDN article. From that post:
The two parameter passing modes addressed by
out
andref
are subtly different, however they are both very common. The subtle difference between these modes leads to some very common programming errors. These include:
- not assigning a value to an
out
parameter in all control flow paths- not assigning a value to variable which is used as a
ref
parameterBecause 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
andout
parameter passing modes was that allowing the compiler to detect these common coding errors was worth the additional complexity of having bothref
andout
parameter passing modes in the language.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With