Reputation: 15
I want to keep my reference to a variable and I don't know how in .NET
First, I receive a reference to an Object like this
Public Function Subscribe(ByRef var As Object) As Integer
MyGlobalVar = var
End Function
I want to keep this reference in a global variable so I can access it later and change the original object.
But every time I do that .NET create a copy, so it does not work.
The only solution I found is to pass an array of Object but this is ugly and i'm searching for other solutions.
Thank you
Upvotes: 1
Views: 2018
Reputation: 726479
There are no reference variables in .NET, only ByRef
parameters. You can pass a reference to a variable into a method, but once the method ends, that reference is gone as well.
You are correct that using a single-item array for its mutability is a hack. You can build your own "mutable reference" class instead, with get
and set
operations changing the object inside your reference class. You can also make that class generic on the type of the object that it holds.
However, good chances are that the need to use a global variable is a consequence of some poor design choice that you made earlier. It is hard to tell for sure without seeing the rest of your design, but if you could think of a way to eliminate that global, the problem of needing to store a reference will be solved as well. For example, knowing that
I'm in a DLL and want the user to pass me the reference of his variable of any type so I can update it each second
you should change the API that you present to the user from this
Public Function Subscribe(ByRef var As Object) As Integer
to this:
Public Function Subscribe(callback As Action(Of Object) ) As Integer
The users of your code will pass a delegate for you to call when you want to update the value of interest. Then it would be up to them to assign the value that you pass to them to whatever variable they may choose.
You can store the Action(Of Object)
delegate, and call it each time that you want to update the value. It will be up to you to update it each second, or skip updates whenever the value does not need to change. Overall, this would achieve a better separation between your code and the code of your callers.
Upvotes: 0
Reputation:
If you mean “actually change what the original variable points to”, no, that’s just not possible. A cleaner way might be to put it in a class, but it really depends on your situation.
Since you look like you need events, though, use ’em!
Public Event SomethingHappened As EventHandler(Of Object) ' Or whatever type
And if you’d really like:
Public Sub Subscribe(cb As EventHandler(Of Object))
AddHandler SomethingHappened, cb
End Sub
Once a second:
RaiseEvent SomethingHappened(42)
Upvotes: 1