C
CuriousGeorge
Can someone explain why this code DOES NOT raise a null reference exception?
//////////////////////////// Program.cs
/////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using CSharpLib;
namespace CSharpConsole
{
class Program
{
private EventHandler handler;
private Class1 obj;
static void Main(string[] args)
{
(new Program()).RunTest();
Console.ReadKey(true);
}
private Program()
{
obj = new Class1();
handler = new EventHandler(DoSomething);
}
private void RunTest()
{
obj.SomeEvent += handler;
obj.RaiseEvent(delegate { obj.SomeEvent -= handler; });
}
private void DoSomething(object sender, EventArgs e)
{
Console.WriteLine("foo");
}
}
}
//////////////////////////// Class1.cs
/////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharpLib
{
public class Class1
{
public event EventHandler SomeEvent;
public delegate void Callback();
public Class1()
{
}
public void RaiseEvent(Callback callback)
{
EventHandler temp = SomeEvent;
callback();
if (temp != null)
{
temp(this, EventArgs.Empty);
}
}
}
}
//////////////////////////// Program.cs
/////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using CSharpLib;
namespace CSharpConsole
{
class Program
{
private EventHandler handler;
private Class1 obj;
static void Main(string[] args)
{
(new Program()).RunTest();
Console.ReadKey(true);
}
private Program()
{
obj = new Class1();
handler = new EventHandler(DoSomething);
}
private void RunTest()
{
obj.SomeEvent += handler;
obj.RaiseEvent(delegate { obj.SomeEvent -= handler; });
}
private void DoSomething(object sender, EventArgs e)
{
Console.WriteLine("foo");
}
}
}
//////////////////////////// Class1.cs
/////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharpLib
{
public class Class1
{
public event EventHandler SomeEvent;
public delegate void Callback();
public Class1()
{
}
public void RaiseEvent(Callback callback)
{
EventHandler temp = SomeEvent;
callback();
if (temp != null)
{
temp(this, EventArgs.Empty);
}
}
}
}