views:

45

answers:

4

I'm not sure really how to ask that question.. hopefully my explanation will clarify:

I have a public method in a class, say Widget that takes a list of Widgets and makes changes to them. However, sometimes, the Widget calling the method is in that list. Is there any way to set the current object as one of the items in the list?

For example, here's what I'm trying to do:

Public Class Widget()
    '...other stuff'
    Public Sub Update()
        'do some stuff...'
        For Each w As Widget In List(Of Widget)
           'update widgets'
           If w.ID = ID Then
              Me = w '<----- here is what I am trying to do, but it wont let me'
           End If
        Next
    End Sub
End Class
A: 

Me references the class instance in which the code runs and cannot be altered. (this in c#) It cannot be used like a variable.

Mischa
The current instance is this in c#.
recursive
A: 

What are you trying to do, at a higher level?

I mean, why are you trying to "change" the current object into one of the objects in that list?

If you want to change the references that other people have to your current object, so that they now point to another object, then no, you can't do that.

Also, it seems like you're taking the object that IS "me" already, and trying to assign it to "Me". What's the purpose of this?

Daniel Magliola
at a higher level, on a page (relevant to a single form) i'm updating all the relevant forms to an overarching order as one form's actions can impact other forms, but i want to pick the form relevant to that page and rebind it to the form.
Jason
+3  A: 

No, but what you can do is have your object fire an event which the referencing (parent) object listens for, and replaces the object appropriately.

Public Class Widget
    Public Event Replace As ReplaceReferenceEventHandler

    Public Sub Update()
        'do stuff
        For Each w As Widget In List(Of Widget)
           'update widgets'
           If w.ID = ID Then
              Replace(Me, w)
           End If
        Next
    End Sub
End Class

Public Delegate Sub ReplaceReferenceEventHandler(ByVal sender As Object, ByVal replaceWith As Object)
Rex M
Interesting idea!(Provided that's actually what he's trying to do)
Daniel Magliola
interesting. create something like `Updated` and have it fire when i hit the correct object, and then in my handler, replace the current object... can i pass the object to replace it with?
Jason
Yes, you can, you define the parameters of the event when declaring it, and then pass it when raising it.
Daniel Magliola
@Jason see my edit
Rex M
+1  A: 

Just return the object you want to use, and set the reference at the call site.

Public Class Widget()
    '...other stuff'
    Public Function Update() As Widget
        'do some stuff...'
        return SelectedWidget
    End Sub
End Class

myWidget = myWidget.Update()
recursive