What's the difference between parameters declared with var
and those declared with out
? How does the compiler treat them differently (e.g., by generating different code, or by changing which diagnostics it issues)? Or do the different modifiers merely allow the programmer to document intended use of the parameters? What effect do the types of the parameters have on the matter?
The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition as well as in the calling method.
There is a clear difference between variables and parameters. A variable represents a model state, and may change during simulation. A parameter is commonly used to describe objects statically. A parameter is normally a constant in a single simulation, and is changed only when you need to adjust your model behavior.
It is also similar to the in keyword but the in keyword does not allow the method that called to change the argument value but ref allows. For using out keyword as a parameter both the method definition and calling method must use the out keyword explicitly.
Calling a method with an out argument In C# 6 and earlier, you must declare a variable in a separate statement before you pass it as an out argument. The following example declares a variable named number before it is passed to the Int32.
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.
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