After reading this question, it seems like the following code should fail:
private void Form1_Load(object sender, EventArgs e)
{
EventHandler myHandler = null;
myHandler(this, null);
}
But when I run it, it works just fine (and does nothing). How does that code behave any differently than the following?
private void Form1_Load(object sender, EventArgs e)
{
EventHandler myHandler = null;
EventHandler myCopy = myHandler;
if (myCopy != null)
{
myHandler(this, null);
}
}
Edit: Catching the exception this way works, according to Lasse V. Karlsen's answer:
private void Form1_Load(object sender, EventArgs e)
{
try
{
EventHandler myHandler = null;
myHandler(this, null);
}
catch (Exception ex)
{
this.Text = "Exception!";
}
}
The problem here is that the Load event is swallowing your exception.
There are other questions here on SO about this and other posts on the net about it:
In short, in certain circumstances (the most often cited reason is a 32-bit .NET program running on 64-bit Windows) any exceptions in the Load event of a WinForms Form will be swallowed.
You can wrap the Form Load event in a try/catch block to catch it, and determine how to react to it.
In short 2: The code does indeed cause a null reference exception as you expected, you're just not seeing it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With