2

I have created an external class (TheClass) with an event (TheEvent) and subscribe to it from within another class's Panel constructor:

public aPanel()
{
   ...
   theClassInstance.TheEvent += new WaitCallback(aMethod);
   ...
}

Later in the program, I call a method passing theClassInstance as the only parameter

bMethod((object)theClassInstance);

where

public void bMethod(object inputTheClassInstance)
{
   ...
}

Knowing that the input object is of type TheClass, I do the following:

public void bMethod(object inputTheClassInstace)
{
   TheClass theClassInput = (TheClass)inputTheClassInstace;
   ...
}

Later in bMethod() I call a method RaiseEvent() exposed by theClassInput which will actually trigger the event. In RaiseEvent() I have

if(this.TheEvent != null)
   TheEvent();

to make sure something is subscribed to the event but this.TheEvent equates to null. If I place the subscription within bMethod()

bMethod(...)
{
   ...
   theClassInput.TheEvent += new WaitCallback(aMethod);  
   ...
}

it works just fine but I would like to keep it in the Panel's constructor. I figured that because theClassInput is pointing to the same object as theClassInstance it wouldn't make a difference which triggers the event. Any thoughts on how I can keep the subscription in the constructor while calling it from within bMethod() using theClassInput?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
john
  • 4,043
  • 7
  • 27
  • 39
  • If I read correctly, it should be possible to subscribe from the Panel.ctor. Do verify you're dealing with the same instance (write theClassInput.GetHashCode() with Debug.WriteLine) – H H Jul 27 '11 at 19:43
  • 1
    It's really hard to follow code when it's presented in tiny snippets like this, especially with names like "bMethod", "TheClass" and "TheEvent". Please show a short but *complete* example which demonstrate the problem. Normally this would *not* be an issue. – Jon Skeet Jul 27 '11 at 19:43
  • How unequivocally certain are you theClassInstance is the same instance as theClassInput? – Jimmy Hoffa Jul 27 '11 at 19:45
  • Hey guys, thanks! GetHashCode() helped solve the problem and now I feel stupid. I used new to overwrite the class instance later in the program (bangs head against wall). Thanks again! – john Jul 29 '11 at 15:40

2 Answers2

2

Passing an object around does not clear event handlers. You must accidentally create a new object somewhere along the way instead of passing the original one.

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
0

Make it into a generic and pass it the TheClass

bMethod<T>(T obj) where T : IHasEvent {
  obj.RaiseEvent();
}

after reading the comment, above, I really bet a GetHashCode call on both sides of the fence, will not match.

Jake Kalstad
  • 2,045
  • 14
  • 20