can anyone suggest me the exact use of out keyword as a paramter, and how its connected for returning multiple values from the function, as in this POST, i am confused with out variable with normal variable. can anyone help me for this.
-
See [this post](http://stackoverflow.com/questions/1169786/when-should-i-use-out-parameters) for a very similar question. – Michael Minton Oct 10 '11 at 17:50
-
I think this example is quite clear http://stackoverflow.com/questions/748062/how-can-i-return-multiple-values-from-a-function-in-c/748096#748096 – xanatos Oct 10 '11 at 17:50
8 Answers
This is frequently confusing, and I think the MSDN documentation actually is a bit "clear only if already known". That is, it is correct, but it really only makes sense if you already understand the concept.
Here's how I think of it.
A regular parameter makes a copy of the value of the argument. When you say:
static int M(int z) { z = z + 1; return z; }
...
int x = 123;
int y = M(x);
That is just like you said:
int x = 123;
int z = x; // make a copy of x
z = z + 1;
int y = z;
A ref or out parameter make an alias for an existing variable. When you say
static void N(ref int q) { q = q + 1; }
...
int x = 123;
N(x);
That is the same as saying:
int x = 123;
// MAGIC: q is now an another name for variable x
q = q + 1;
q
and x
are two different names that refer to the same variable. Incrementing q
also increments x
because they are the same. z
and x
in the previous example are two different names that refer to two different variables. Incrementing z
does not change x
.
Summing up: "out" and "ref" just mean "do not make a new variable; rather, temporarily make a second name for an existing variable".
Is that now clear?
UPDATE: I did not say what the difference between "out" and "ref" is. The difference is simple. On the "caller" side, a "ref" must be a definitely assigned variable before the method is called. An "out" need not be. On the "callee" side, a "ref" may be read before it is written to, but an "out" must be written to before it is read. Also, an "out" must be written to before control leaves the method normally.

- 647,829
- 179
- 1,238
- 2,067
-
Not bit, i created a sample example project, where i created below method static void N(out int q) { q = q + 1; } now it throws the error saying use of unassigned local variable q, now how to assign, i have already assinged value to q. – Abbas Oct 10 '11 at 18:32
-
An out parameter need not be definitely assigned in the caller before the call site. Because of this, it must be assigned before first use in the callee (the declaring method). You can correct the method in your comment by changing `out` to `ref`. – phoog Oct 10 '11 at 18:47
-
@Abbas: You are right; I was not clear because I did not say what the difference is between "out" and "ref". Is the update now clear? – Eric Lippert Oct 10 '11 at 18:58
MSDN documentation already does a great job explaining this:
The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example:
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}

- 63,293
- 14
- 100
- 115
-
There's another important factor. An `out` parameter must be definitely assigned before the method returns normally. – phoog Oct 10 '11 at 18:45
It's very frequently used in a pattern that "tries" to get a value, something like:
int result;
if(Int32.TryParse("123", out result))
{
Console.WriteLine(result + 1);
}

- 88,082
- 50
- 208
- 326
out
keyword should be used when you want to:
a) Allow your function to modify specific variable from calling code stack AND
b) enforce setting this variable value inside your function

- 10,328
- 4
- 43
- 68
In most languages c# included you can pass values in 2 ways, by value, by reference.
by value gives the method a copy of your data, so changing the data wont have any effect on the original data
by reference essentially gives the method the memory address of your data, so if the method modifies the data, it changes the original.
Out is a special type of ref, in that you do not need to initialise the variable before you call the method, it can be called with null being passed in. and it MUST be set by the method.
Another way you can think of it (from the outside code's point of view) is:
val = read only
ref = read/write
out = write only.

- 1,547
- 1
- 14
- 37
-
4**Out parameters are *not* "write only".** It would be highly convenient if they were, I agree, but they are not, and wishing does not make it so. The restriction on "out" parameters is that they *must be written to before they are read from*, not that *they must never be read from*. It is perfectly legal to read from an out parameter after it has been written to. It is this feature that makes it illegal for out parameters to be treated in a contravariant manner, as returned types can be. – Eric Lippert Oct 10 '11 at 18:08
-
1@Eric: I hope you meant to say "covariant manner", or else I have to reread my books and your series on covariance/contravariance (as if things like Action
>> didn't make my head spin out of control, ha). – Alan Oct 10 '11 at 20:15 -
@Alan: Whoops, you are of course correct. Normal "in" parameters can be *contravariant*. Out parameters could be covariant if they were actually write-only, but they are not. – Eric Lippert Oct 10 '11 at 20:26
-
@Eric Lippert, I did say that this is just a possible way to think of it, and I also specify that the perspective is from the outside codes point of view. That last paragraph is intended to provide a simple conceptual model for intended usage as opposed to being absolutely accurate. – stevenrcfox Oct 12 '11 at 13:41
-
@stevenrcfox interesting way to look at it. You should add "in" keyword as well for completeness. – tinker Oct 07 '19 at 06:25
http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx
out
keyword is good if you want to return multiple values of pre-defined types (for example an int
, a List<string>
and a DateTime
), and you don't want to create a new class just for this purpose.

- 8,307
- 7
- 53
- 91
Ok,
let look at the usual pattern for this kind of function - the TrySomething
.
Suppose you have a function that might succeed giving you an value or not but you don't won't to use an exception for this because you don't want the overhead or it's a common trait.
Then you normaly return true
if the method suceeded and false
if not. But where would you put your outputvalue to?
One possible answer is using an out
parameter like this:
bool TrySomething(MyInputType input, out MyOutputType output)
{
output = default(MyOutputType);
/* ... Try getting the answer ... */
if (!successful)
return false;
output = successfulOutput;
return true;
}
Remark:
Or you might consider using a Tuple<bool,MyOutputType>
and indeed F# interpretes the pattern above as resulting in such a tuple by itself.

- 51,810
- 9
- 92
- 119