To answer this question, I had to do bit of research.
Step 1) I modified your code a bit,
public class EventGenerator
{
public delegate void MyEventHandler(object o, EventArgs e);
public event MyEventHandler MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
if (MyEvent != null)
{
MyEvent(this, e);
}
}
}
public class MyTest
{
EventGenerator eventGen;
public MyTest()
{
eventGen = new EventGenerator();
eventGen.MyEvent += new EventGenerator.MyEventHandler(TestFunction);
eventGen.MyEvent -= new EventGenerator.MyEventHandler(TestFunction);
}
public void TestFunction(object o, EventArgs e)
{
}
}
Compile the code and grab the exe and drop into the
ILDasm[
^]program.
Step 2) From the ILDasm program, we can see,
eventGen.MyEvent += new EventGenerator.MyEventHandler(TestFunction);
has been translated as
IL_0025: callvirt instance void ConsoleApplication18.EventGenerator::add_MyEvent(class ConsoleApplication18.EventGenerator/MyEventHandler)
eventGen.MyEvent -= new EventGenerator.MyEventHandler(TestFunction);
has been translated as,
IL_003d: callvirt instance void ConsoleApplication18.EventGenerator::remove_MyEvent(class ConsoleApplication18.EventGenerator/MyEventHandler)
Step 3) Now the Question where is the
add_MyEvent
and
remove_MyEvent
comes from, the answer could be find out from two places,
1.
CLR Via C# by Jeffrey Richter Page 270
2..Net Reflector, if we put that compiled exe or dll (which contains the above code) then following code will be find out from MyEvent class,
add_MyEvent
,
public void add_MyEvent(MyEventHandler value)
{
MyEventHandler handler2;
MyEventHandler myEvent = this.MyEvent;
do
{
handler2 = myEvent;
MyEventHandler handler3 = (MyEventHandler) Delegate.Combine(handler2, value);
myEvent = Interlocked.CompareExchange<MyEventHandler>(ref this.MyEvent, handler3, handler2);
}
while (myEvent != handler2);
}
and
remove_MyEvent
public void remove_MyEvent(MyEventHandler value)
{
MyEventHandler handler2;
MyEventHandler myEvent = this.MyEvent;
do
{
handler2 = myEvent;
MyEventHandler handler3 = (MyEventHandler) Delegate.Remove(handler2, value);
myEvent = Interlocked.CompareExchange<MyEventHandler>(ref this.MyEvent, handler3, handler2);
}
while (myEvent != handler2);
}
Hope it answer your questions :)