What's the difference between "var" and "out" parameters?
Solution 1:
A var
parameter will be passed by reference, and that's it.
An out
parameter is also passed by reference, but it's assumed that the input value is irrelevant. For managed types, (strings, Interfaces, etc,) the compiler will enforce this, by clearing the variable before the routine begins, equivalent to writing param := nil
. For unmanaged types, the compiler implements out
identically to var
.
Note that the clearing of a managed parameter is performed at the call-site and so the code generated for the function does not vary with out
or var
parameters.
Solution 2:
There is not much difference, for the compiler that is. See Mason's answer for that.
Semantically, there is a big difference:
-
var
tells the programmer that the routine could work with its current value, -
out
tells the programmer that the routine will ignore/discard its current value.