views:

159

answers:

3

In what situtations is it best to use reference arguments to return values?


Sub Example(byref value as integer)
  value = 3
End Sub

In what situations is it best to return the value (perhaps in a structure for more complex types)?


Function Example() as integer
  return 3
End Function
A: 

It really depends what the function's doing. Generally, though, if there's only one return, by value is easier for the caller. They can simply do:

int foo = Example(foo)

or:

int modifiedFoo = Example(foo)

as they prefer.

Matthew Flaschen
+1  A: 

In general, I'd avoid using reference arguments to return values.

THe design guidelines suggest avoiding this, which is why the Microsoft code analysis tools warn you when they find it.Do not pass types by reference.

It's nearly always more maintainable to return values instead of passing arguments by reference, unless there is a very specific need to do so. If you're generating a new value, return it.

Reed Copsey
+1 - returning a value through a parameter is never intuitive, it always requires a double-take to realize how the call is working
STW
+1  A: 

when you want to return a state or status of an operation plus the result from the operation.

think of TryParse..it returns a conversion result as true or false and it returns the converted value by a ref variable.

 Dim number As Integer
 Dim result As Boolean = Int32.TryParse(value, number)


Public Shared Function TryParse ( _
    s As String, _
    <OutAttribute> ByRef result As Integer _
) As Boolean

but other than that, as others suggested i would not use by ref a lot, it can make code very hard to read and debug.

Stan R.