views:

431

answers:

2

I have two objects - one that contains some code with will fire an event, and one that contains the handler for that event. I can't "AddHandler" in the Load of the first object, because an instance of the second object doesn't exist yet. When I raise my event, I want to check to see if a copy of object2 has been instantiated (easy to do), and if a handler has been attached to the event yet (not sure how to do this).

I'm also open to another recommendation about how to do this instead. If I do my AddHandler in Object1.Load, and Object2 doesn't exist yet, then it will never handle my event, even if I create it later. Right now, in the code that fires the event, I've just resorted to doing a RemoveHandler and then an AddHandler every single time the event is raised, and then I know I'll attach when the object finally exists, but I know this is a crappy method.

I saw an article about something similar (http://stackoverflow.com/questions/660480/determine-list-of-event-handlers-bound-to-event), and maybe I'm missing something in the translation, but I can't get the code to work on my custom event in VB.NET.

A: 

If you just want to know whether any handler has been attached, you should be able to check whether the event is null.

if (MyButton.Click == null)
{
    MyButton.Click += myEventHandler;
}

(I'll let you translate that into VB)

StriplingWarrior
This won't work if some other event has already been added.
ChrisF
I'm doing this for a custom event, not a standard one, and this code doesn't seem to work in this case - checking the value of MyEvent fails syntax, telling me "This is an event, and can't be called directly", so I can't even compile. I suppose this is something C# just handles differently than VB...
rwmnau
@ChrisF: That's why I was wonderinf if he wants to know whether *any* handler was attached (versus a specific handler). Maybe he knows that he's the only one that will be touching it.@rwmnau: As I understand it, Events can only be directly accessed by their declaring class, so this code would have to be put into the class itself.
StriplingWarrior
+1  A: 

You could also just have a bool field that you check before hooking the event.

if not eventHooked then
 addhandler
 eventHooked = true
end if

Also if you need a good c# to vb converter http://www.tangiblesoftwaresolutions.com/ has one that can translate a 100 lines on the fly or less for or translate a project of a 1000 lines for free. More than that you have to purchase it, but that usually those limits will work just fine. No I am not trying to advertise for them :-)

NastyNateDoggy
I had considered this, and it's probably what I'll go with. I just figured there might be an easy way to detect if the event is already hooked, but if there's not, then this is my preferred method.
rwmnau
Though I was hoping to avoid this solution, it solves my problem and works like a champ. Thanks for your help.
rwmnau