Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "var" and "out" parameters?

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?

like image 779
Rob Kennedy Avatar asked Jan 24 '13 17:01

Rob Kennedy


People also ask

What is an out parameter?

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.

What is the difference between a parameter and a variable?

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.

What is in parameter and out parameter?

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.

Do you need to declare and out variable before you use it?

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.


1 Answers

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.

like image 124
Mason Wheeler Avatar answered Oct 17 '22 11:10

Mason Wheeler