tags:

views:

51

answers:

4

Hi guys!

We often use event handler in C#, just as below:

some_event+=some_event_handler;

Does this happen at compile time or run time? What if the some_event is static member? AFAIK, the some_event contains nothing but the entry address of some_event_handler, and the method address of some_event_handler could be determined at compile time. If some_event is a static member, could the value of the some_event be determined at compile time? I konw that if the some_event is an instance member, it's value will be setup at the creation time of the object instance. Correct me if I'm wrong.

Many thanks, guys~ :)

A: 

If you need to track them maybe you need manual event handling with the keywords add and remove. Take a look at this http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx (from example 2 on)

And yes, i forgot, events are registered at runtime

astorcas
Thanks astorcas, I will take a look at that.
smwikipedia
A: 

The subscription happens at run-time. It can be inside conditional.

Pavel Radzivilovsky
Thanks Pavel. I just need the proof. ;)
smwikipedia
A proof, like mathematical proof? :) Well, if it would happen at compile time, you would not be able to conditionally subscribe when the fact of whether subscription is requested is not known at compile time. Anyway, look at MSIL.
Pavel Radzivilovsky
Nice and logical. Thanks.
smwikipedia
+1  A: 

We can say it concerns delegates. A delegate variable is assigned a method dynamically. This gives us ability to write plugin methods.

Concerning instance and static method targets just a note from C# in Nutshell

When a delegate object is assigned to an instance method, the delegate object must maintain a reference not only to the method, but also to the instance to which the method belongs. The System.Delegate class’s Target property represents this instance (and will be null for a delegate referencing a static method).

Incognito
Thanks Incognito, the info you provide is very informative.
smwikipedia
A: 

The code is just a statement, similar to a method call, and thus occurs in the natural execution stream at the point you placed it, be it inside a loop, if-statement or similar.

As such, before the statement has executed, the event has not been assigned the event handler. It does not matter (in this context) whether the event is a static or instance event.

You can consider how the code behaves by comparing it to this code:

some_event = Delegate.Combine(some_event, some_event_handler);

then it should be clearer that this is just a basic method call, nothing more.

The syntax of event += handler is just short-hand for the above code, and the compiler will translate the syntax to that method call. If you use Reflector you can see that this is how it is done.

See Delegate.Combine on MSDN.

Lasse V. Karlsen
Thanks Lasse, you clear some of the mist for me. ;)
smwikipedia