On Sun, 05 Oct 2008 13:12:36 -0700, puzzlecracker <ir*********@gmail.com>
wrote:
I am sort of confused here. Jon Skeet allegedly claims that evens are
like properties. To me, on the contrary, they look more like
instances of delegates.
What's the deal here?
You're both right.
But, as is usually the case when comparing something Jon says to something
any of the rest of us say, Jon is "more right". :)
In particular, what you are looking at is automatically-generated events.
When you declare an event without an implementation, the compiler provides
the implementation for you. Inside the class in which the event is used,
the event looks like a delegate, because that's exactly what the compiler
provides for you (*).
But, behind the scenes the compiler is also adding methods to support the
event. And literally, an event _always_ consists of exactly two methods:
an "add" method and a "remove" method. The field in which the delegate is
stored is implicitly created by the compiler for auto-generated events,
but it's not a mandatory part of an event; only the "add" and "remove"
methods are (you could explicitly implement an event that managed the
subscription to the event in some way other than a simple delegate field).
So, in the same way that the thing that defines a property is the presence
of the "get" and "set" methods (optionally omitting one or the other), the
thing that defines an event is the presence of the "add" and "remove"
methods (though for events, they are not optional). This is what Jon
means when he says events are like properties.
Pete
(*) There are interesting side-effects to this auto-generated behavior:
-- When you take advantage of the auto-generated event, from inside
the class you do _not_ have access to the implementation of the event.
This is normally not an issue, but it means that even though the default
implementation of an event provides for thread-safe access to the event
field, modifying the event field from within the class in that case could
result in a corrupted event because that doesn't go through the accessors.
-- The compiler is required to use the containing object ("this") when
locking for instance events and the type object for static events. In
both cases, this means that the lock is taken using a public reference,
which is usually considered a bad idea: in general, it means that other
code could be locking on the same object at the same time, increasing the
chance of deadlock, and at a minimum increasing contention for the lock.
Fortunately, for an event there's not any subsequent locking that takes
place within the add and remove methods, and so the event should not in
and of itself be able to lead to deadlocking. But I find it interesting
to note the exception to the rule being implicitly expressed in the C#
spec. :)