Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Return ByRef

In one of my classes I want to code a function similar to

Public Class Test

Public Function Tester(Optional byval testdata as integer = 0) as integer

static testholder as integer = testdata
return testholder

End Function

End Class

In another class I want to be able to write something like this code

Dim TestObject as New Test
Dim testholder as Integer
testholder = TestObject.Tester(5)
testholder += 10
MsgBox(TestObject.Tester())

when the Message box displayes it should hold the number 15.

The goal of this code is lazy initialization and essentially treating the function as a variable. Please help me sort this out.
[721 byte] By [m1423] at [2007-11-11 10:15:24]
# 1 Re: Return ByRef
I don't know of any way to return a variable reference from a function. How about this?

Public Class Test
Private Shared TestValue As Integer

Public Shared Property TestHolder() As Integer
Get
Return TestValue
End Get
Set(ByVal value As Integer)
TestValue = value
End Set
End Property
End Class

Test.TestHolder = 5
Test.TestHolder += 10
MsgBox(Test.TestHolder)
Phil Weber at 2007-11-11 20:48:18 >
# 2 Re: Return ByRef
I am sorry to say that your solution does not meet the need I had for lazy initialization. I recently figured out that I could use the keyword Nothing to solve this for now though I would still be interested in how to do my original question.
m1423 at 2007-11-11 20:49:18 >
# 3 Re: Return ByRef
An integer isn't a reference type, it's a value type. This is why when you add 10 to testholder nothing happens to the variable in the class. This example shows a stripped down version of what you seem to want, which can't happen.

Dim number1 As Integer = 10
Dim number2 As Integer = number1
number2 += 10
'Number1 will not be 20 which is the kind of functionality you want
'Only reference types are effected in this way.
MsgBox("Number 1 = " & number1.ToString & vbCrLf & "Number 2 = " & number2.ToString)

Also your function appears to be doing nothing more then giving access to a variable. This is what properties are for, so I think, unless I'm missing something, what you really want is a property.

Hopefully I've helped, but if you could give a more specific goal and possibly actual context I may be able to help further.
TwoFaced at 2007-11-11 20:50:23 >