this cf sender in event handlers

  • Thread starter Thread starter Gary Stephenson
  • Start date Start date
G

Gary Stephenson

Can someone please explain why the assertion in the following code fails?
Could the assertion be made to succeed somehow?

// code begins

class MyButton : Button
{
public MyButton()
{
Click += HandleClick ;
}

public void HandleClick( object sender, EventArgs e)
{
Debug.Assert( Object.ReferenceEquals( sender as MyButton, this ) ;
// why does this fail?
}
}

// code ends

many tias,

gary
 
Gary Stephenson said:
Can someone please explain why the assertion in the following code fails?
Could the assertion be made to succeed somehow?

// code begins

class MyButton : Button
{
public MyButton()
{
Click += HandleClick ;
}

public void HandleClick( object sender, EventArgs e)
{
Debug.Assert( Object.ReferenceEquals( sender as MyButton, this ) ;
// why does this fail?
}
}

Well, the first thing to do would be to look at what the sender
*actually* is.
 
Can someone please explain why the assertion in the following code fails?
Could the assertion be made to succeed somehow?

// code begins

class MyButton : Button
{
public MyButton()
{
Click += HandleClick ;
}

public void HandleClick( object sender, EventArgs e)
{
Debug.Assert( Object.ReferenceEquals( sender as MyButton, this ) ;
// why does this fail?
}

}

// code ends

many tias,

gary

--http://www.oxide.net.au

Hi,

I tried it my self and it worked (no assertion). The references should
be equal.

Cheers,
Moty
 
Hmm, I suppose I should have been more precise by pointing out that "sender
as MyButton" does not return null - hence sender is definitely an instance
of MyButton (as expected since the event is actually raised by clicking the
button in question) - but apparently not (always) the same instance as
"this".

I see that another respondent found the assertion not to fail in their
testing, so I remain at a loss. Perhaps the question should be rephrased
as: Under what circumstances might the assertion be made to fail?

thanks,

gary
 
Back
Top