What is the difference between the var and out parameters?

What is the difference between parameters declared with var and declared with out ? How does the compiler handle them differently (for example, by generating different code or changing what diagnostic data it gives)? Or do the various modifiers simply allow the programmer to document the intended use of the parameters? What effect do parameter types have on this issue?

+44
pass-by-reference parameters delphi
Jan 24 '13 at 17:34
source share
3 answers

A var parameter will be passed by reference and that it is.

The out parameter is also passed by reference, but he suggested that the input value does not matter. For managed types (strings, interfaces, etc.), the Compiler will apply this by clearing the variable before the start of the procedure, equivalent to writing param := nil . For unmanaged types, the compiler implements out identically to var .

Please note that the clearing of the managed parameter is performed on the call site, so the code generated for the function does not change with the out or var parameters.

+37
Jan 24 '13 at 17:38
source share

There is not much difference for the compiler. For this, see Mason .

Semantically there is a big difference:

  • var tells the programmer that the subroutine can work with its current value,
  • out tells the programmer that the routine ignores / discards the current value.
+6
Jan 25 '13 at 10:26
source share

A little late, but just for the record, I came across a case where var or out made a big difference.

I was working on a SOAP web service that exported the following method:

 function GetUser( out User :TUser ) :TResult; 

which was imported into C # as an equivalent

 function GetUser( out Result :TResult) :TUser; 

when i changed out to var , it imported it correctly.

I assume that calling Delphi SOAP treats the result of the function as an out parameter, and the presence of two out parameters confuses the Delphi SOAP routines. I am not sure if there is a workaround allowing the use of out parameters.

+1
Feb 20 '14 at 17:17
source share



All Articles