RE: Difference between 'out' and 'ref' parameters.
- From: "Jorge L Matos" <matos_jorge(NOSPAM)@hotmail.com>
- Date: Mon, 18 Apr 2005 06:18:17 -0700
You're almost right, "ref" and "out" are similar in that they can both return
a value from a method, but they have slightly different semantics.
You need to initialize a "ref" parameter before passing it to a method, but
you don't have to initialize an "out" parameter before passing it to a method
because the c# compiler knows that the method will assign a value to the
parameter before returning. In fact, the c# compiler will throw a compiler
error if it detects that the method has not assigned a value to an "out"
parameter before returning.
By value example: The output from the code below will be "x = 0"
int x = 0;
add(x)
Console.Write("x = {0}", x);
void add(ref x)
{
x = x + 1
}
"Ref" example: The output from the code below will be "x = 1"
int x = 0;
add(ref x)
Console.Write("x = {0}", x);
void add(ref x)
{
x = x + 1
}
"out" example: The output from the code below will be "x = 1"
int x;
add(out x)
Console.Write("x = {0}", x);
void add(out x)
{
x = x + 1
}
Note: The variable "x" is not initialized prior to the call to "add"
For more info:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfref.asp
"Chris Mayers" wrote:
> 'out' and 'ref' parameters in C#...
>
> Both these can be used to pass parameter values BACK from a Method, but
> obviously they are different techniques.
>
> As I understand it,
>
> 'ref' parameter passes the object into the Method by Reference, ie passes
> the memory location of the original object in the parameter list. The Method
> may change the value of the object and by doing so, will be changing the
> value of the original object.
>
> 'out' parameter passes an object BY VALUE back into the object in the
> calling parameters.
>
> 1) Am I right?
> 2) Is it true to say that you are usually better to use 'out' unless the
> original value of the parameter being passed in effects its value when you
> pass it back. Or if your method needs to return more than one calculated
> result.
>
> eg
>
> private void GetPosition(string lorryId, out int xLocation, out int
> yLocation)
>
> Hope this makes sense, I'm very tired...
>
> Thanks,
>
> Chris.
>
>
>
.
- Follow-Ups:
- Re: Difference between 'out' and 'ref' parameters.
- From: Chris Mayers
- Re: Difference between 'out' and 'ref' parameters.
- References:
- Difference between 'out' and 'ref' parameters.
- From: Chris Mayers
- Difference between 'out' and 'ref' parameters.
- Prev by Date: Re: Difference between 'out' and 'ref' parameters.
- Next by Date: Re: Difference between 'out' and 'ref' parameters.
- Previous by thread: Re: Difference between 'out' and 'ref' parameters.
- Next by thread: Re: Difference between 'out' and 'ref' parameters.
- Index(es):
Relevant Pages
|