- Home /
What is the use of "out" in variable fields? Example:
I'm looking through some example code, and I came across this:
public static bool GetTouchDeltaPos (int id, out Vector2 deltaPos)
And I'm not quite sure what the "out" before Vector2 is.
It is used elsewhere in the script in other contexts separate from Vector2, and it shows up as a different color identifier in MonoDevelop, so I assume it has some special significance to the compiler.
Thank you for the help
Answer by torrente · May 24, 2012 at 07:49 PM
the out keyword is similar to a pass by ref, where the method/function that is called is able to modify it. Methods/functions can only return one value, so if you want to pass multiple values out from a method/function, you can use the out keyword to pass them all out. Out allows for the initial value to be assigned within the calling method/function whereas a ref would need to have the value originally initialized on the outside. Does that make sense?
So just to sum up, out is the same as ref but with two constraints:
The function can't read the value before it is initialized. It's treated like an uninitialized variable. On the other hand that also means you can't pass any information to the function (since you have to assign a value first).
The function have to assign a value to this variable.
In C# you also have to use the out keyword when you call the function.
Example:
RaycastHit hit; // uninitialized variable
if (Physics.Raycast(transform.position, -Vector3.up, out hit))
// after this call to Raycast hit must be initialized since
// Raycast have to assign a value to it's out parameter.
Ah, thank you! I think I understand. You can get multiple values out of a method/function with "out", and also you can initialize a previously uninitialized variable in the function that is being called via the "out" modification. Yes?
Cool, thanks!
Now that I've learned a bit more about coding, I believe this is the C# version of passing a pointer into a function rather than passing a copy of the variable.
analogous to the C syntax:
Raycast hit;
$$anonymous$$ethodToEmploy(&hit) // passing the address rather than the value itself
If I understand this correctly, I believe it is the same