ref vs out

How are they different
19 Replies
Jimmacle
Jimmacle4w ago
out arguments must be assigned before the method returns also the semantics indicate that the current value of the variable when called won't be used
jcotton42
jcotton424w ago
ref must be assigned before the method is called
ElectricTortoise
ElectricTortoiseOP4w ago
so something like
int x
function(ref int x)
{
//do something
}
int x
function(ref int x)
{
//do something
}
for ref
function(out int x)
{
x = 3
//do something

}

//I can now do something with x
function(out int x)
{
x = 3
//do something

}

//I can now do something with x
for out
Jimmacle
Jimmacle4w ago
ref is an input (and potentially an output), out is an output
ElectricTortoise
ElectricTortoiseOP4w ago
so basically the function spawns a new value out of thin air
Jimmacle
Jimmacle4w ago
i don't know what that means it doesn't spawn anything out of thin air, you're giving it a reference to a variable which it can assign a new value to
ElectricTortoise
ElectricTortoiseOP4w ago
uhhh basically there were 0 values going into the function and 1 value coming out the variable is declared and initialised inside the function though
Jimmacle
Jimmacle4w ago
no it's not
ElectricTortoise
ElectricTortoiseOP4w ago
oh it isnt?
Jimmacle
Jimmacle4w ago
it's still a parameter, you have to pass an argument to the method don't let the inline out variable declaration syntax fool you
MyMethod(out int x);
MyMethod(out int x);
is actually
int x;
MyMethod(out x);
int x;
MyMethod(out x);
ElectricTortoise
ElectricTortoiseOP4w ago
aha ok oh wait that makes it basically the same as ref no?
Jimmacle
Jimmacle4w ago
no
ElectricTortoise
ElectricTortoiseOP4w ago
ref needs a value before going in?
Jimmacle
Jimmacle4w ago
it needs to be initialized, yes with out the method is required to assign a value so it doesn't matter if it's initialized or not
ElectricTortoise
ElectricTortoiseOP4w ago
so this should be
int x
x=3;
function(ref int x)
{
//do something
}
int x
x=3;
function(ref int x)
{
//do something
}
Jimmacle
Jimmacle4w ago
i can't tell you what it should be, i don't know what your end goal is
ElectricTortoise
ElectricTortoiseOP4w ago
oh alright
Jimmacle
Jimmacle4w ago
i personally rarely use ref, it's only applicable when working with large structs or you need to change the value of a variable that's being passed in
ElectricTortoise
ElectricTortoiseOP4w ago
ooo alright

Did you find this page helpful?