At the interviews, the interviewers love to ask all sorts of tricky questions. One of the favorite questions for understanding the .net platform is the question of events and delegates. At best, they ask for differences, at worst, they can ask such a backfilling question.
Given code:
')
public class A
{
public void OnDoWork()
{
if ( DoWork != null )
DoWork( this , EventArgs .Empty);
}
public event EventHandler DoWork;
}
* This source code was highlighted with Source Code Highlighter .
1. What will happen to the program if class A is modified as follows: remove the
event
keyword?
2. What will happen to the program, if at all in the whole code to remove the
event
keywords?
Untrained questions are introduced into a creepy cognitive dissonance as soon as they become aware of them. Here the main thing is to refrain from an indignant cry and recall the syntactic differences in the applicability of events from delegates:
0. An event is the same delegate that is given some properties through the word
event
.
1. Both the event and the delegate can be declared a class field, but unlike the delegate, the event cannot be a local method variable (it doesn’t play a special role, but it’s worth remembering)
2. The event can not be run outside the class in which it was declared (this is the most important difference !!!)
3. The interface can not contain fields.
4. The event is always declared as a “field” and not a property (
add-remove
not
add-remove
).
These are, perhaps, the only differences between the event and the delegate (I do not dare to consider the semantic difference). Well, or I forgot something, but you remind me now :)
So, if we have an interface in which an event is declared, and we remove the
event
keyword, then we have a compiler error - they say, the interface cannot contain fields (the former event has become the delegate field). But if the event is declared as a class field, then from the point of view of the compiler it will be absolutely correct to remove the keyword.
Therefore, the answers to the questions will be as follows:
1. Nothing will change
2. Nothing will change, unless the program has events declared in the interfaces.
Yes, and one more thing is surprising: when answering a question, some begin to reason that the event is
MulticastDelegate
, but the
Delegate
can contain a reference to only one method. In general, this is a completely terrible heresy, but nevertheless several different people tried to give me an answer to these two questions. Where this myth went from is unknown. If you want to see what is the difference MulticastDelegate from Delegate - you can run away to look at Brad Abrams’s mega-authoritative
article - and make sure that there are no differences between these classes, except for the name.
P.S. Yes, I know that
OnDoWork()
not thread safe :)