473,320 Members | 1,804 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Why events if we have delegates

I took a closer look at delegates and events, and it became apparent
that events don't offer any extra functionalities over delegates. I
don't even see it as syntactical sugar over "overtly obfuscated"
delegate syntax. Moreover, you can accomplish everything with
delegates that you can accomplish with events, such as combining
instances, etc.

Am I missing something here?

Thanks
Oct 28 '08 #1
5 1410
On Tue, 28 Oct 2008 09:57:08 -0700, puzzlecracker <ir*********@gmail.com>
wrote:
I took a closer look at delegates and events, and it became apparent
that events don't offer any extra functionalities over delegates. I
don't even see it as syntactical sugar over "overtly obfuscated"
delegate syntax. Moreover, you can accomplish everything with
delegates that you can accomplish with events, such as combining
instances, etc.

Am I missing something here?
Yes. You are missing the fact that if you use a delegate, you are forced
to use the delegate's mechanism for adding and removing method groups. If
you write an event, you have the ability to manage the subscription
however you like. For example, the Control class maintains a dictionary
for each event. There's a little overhead for the dictionary, but there's
_zero_ storage for each event unless it's actually subscribed. For a
class like Control (and its subclasses) that have a huge number of events
that are almost never subscribed to, this is a very significant memory
savings.

The other thing you're missing is that an event _encapsulates_ the
delegate. That is, while the semantics are similar, only the class
declaring the event has access to the storage. Just as with a property,
code outside the class is forced to go through the accessor methods (add
and remove for events), and cannot modify the underlying delegate
directly. Simply using a delegate would not accomplish this.

Pete
Oct 28 '08 #2
On Oct 28, 1:54*pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Tue, 28 Oct 2008 09:57:08 -0700, puzzlecracker <ironsel2...@gmail.com>*
wrote:
I took a closer look at delegates and events, and it became apparent
that events don't offer any extra functionalities over delegates. I
don't even see it as syntactical sugar over "overtly obfuscated"
delegate syntax. Moreover, you can accomplish everything with
delegates that you can accomplish with events, such as combining
instances, etc.
Am *I missing something *here?

Yes. *You are missing the fact that if you use a delegate, you are forced *
to use the delegate's mechanism for adding and removing method groups. *If *
you write an event, you have the ability to manage the subscription *
however you like. *For example, the Control class maintains a dictionary *
for each event. *There's a little overhead for the dictionary, but there's *
_zero_ storage for each event unless it's actually subscribed. *For a *
class like Control (and its subclasses) that have a huge number of events*
that are almost never subscribed to, this is a very significant memory *
savings.
Is there a sample implementation of events stored in dictionary to
save memory? It's sounds like an interesting approach, even though
it's unrelated to the question itself, thought it may become clearer
to me when I see the example, a good one.
The other thing you're missing is that an event _encapsulates_ the *
delegate. *That is, while the semantics are similar, only the class *
declaring the event has access to the storage. *Just as with a property, *
code outside the class is forced to go through the accessor methods (add *
and remove for events), and cannot modify the underlying delegate *
directly. *Simply using a delegate would not accomplish this.
So it is meant for a user to prevent exposing the delegate instance to
the event? So events becomes just an anonymous placeholder for a
delegate.

Thanks

Oct 28 '08 #3
Is there a sample implementation of events stored in dictionary to
save memory? *It's sounds like an interesting approach, even though
it's unrelated to the question itself, thought it may become clearer
to me when I see the example, a good one.
I think "Exaple 2" on link http://msdn.microsoft.com/en-us/libr...ea(VS.71).aspx
So it is meant for a user to prevent exposing the delegate instance to
the event? So events becomes just an anonymous placeholder for a
delegate.
Create a project where you declare an event and use Reflector to see
what is happening behind the scenes. What you will see is that the
even gets translated into two functions used to add and remove
subscriptions.

That is why you can have event declarations on an Interface, because
behind the scenes, the interface will have a get and set method as the
event definition.
Oct 28 '08 #4
delegates are references to methods,
you need some mechanisms to trigger delegates

"puzzlecracker" <ir*********@gmail.comwrote in message
news:16**********************************@a29g2000 pra.googlegroups.com...
I took a closer look at delegates and events, and it became apparent
that events don't offer any extra functionalities over delegates. I
don't even see it as syntactical sugar over "overtly obfuscated"
delegate syntax. Moreover, you can accomplish everything with
delegates that you can accomplish with events, such as combining
instances, etc.

Am I missing something here?

Thanks

Oct 28 '08 #5
On Tue, 28 Oct 2008 13:30:51 -0700, puzzlecracker <ir*********@gmail.com>
wrote:
Is there a sample implementation of events stored in dictionary to
save memory? It's sounds like an interesting approach, even though
it's unrelated to the question itself, thought it may become clearer
to me when I see the example, a good one.
I'm not sure what you mean by "unrelated to the question itself". In that
an event is an abstraction that need not be implemented using a simple
delegate field, I think your follow-up is in face reasonably related to
the original question.

As for such an example, here's a sort of brain-dead version of what it
might look like:

class Base
{
Dictionary<string, Delegate_dictEventHandlers = new
Dictionary<string, Delegate>();

protected void _AddEventHandler(string strEventName, Delegate
handler)
{
Delegate handlerCur;

if (_dictEventHandlers.TryGetValue(strEventName, out
handlerCur))
{
handlerCur += handler;
}
else
{
handlerCur = null;
}

_dictEventHandlers[strEventName] = handlerCur;
}

protected void _RemoveEventHandler(string strEventName, Delegate
handler)
{
Delegate handlerCur;

if (_dictEventHandlers.TryGetValue(strEventName, out
handlerCur))
{
handlerCur -= handler;
_dictEventHandlers[strEventName] = handlerCur;
}
}

public event EventHandler BaseEvent
{
add { _AddEventHandler("BaseEvent", value); }
remove { _RemoveEventHandler("BaseEvent", value); }
}
}

class Derived : Base
{
public event EventHandler DerivedEvent
{
add { _AddEventHandler("DerivedEvent", value); }
remove { _RemoveEventHandler("DerivedEvent, value); }
}
}

I say "brain-dead" because using a string as the key for the dictionary
isn't the most efficient approach a class like this might take. But it's
simple, and actually doesn't add _that_ much overhead.

Anyway, hopefully the example is sufficient to illustrate the idea. Note
that unless an event is actually subscribed to, the dictionary never winds
up storing anything for that actual event. The approach itself has some
overhead, in the form of the dictionary itself (which even when empty,
takes up _some_ room), and of course the keys (which even if they are
Guids or something like that, take up some space in the executable). But
not that the keys are not per-instance, and if you've got lots of events,
the space taken by the dictionary itself is tiny compared to how big an
instance would be to store all those null references that are almost never
used if the default implementation was used.

>The other thing you're missing is that an event _encapsulates_ the Â*
delegate. Â*That is, while the semantics are similar, only the class Â*
declaring the event has access to the storage. Â*Just as with a
property, Â*
code outside the class is forced to go through the accessor methods
(add Â*
and remove for events), and cannot modify the underlying delegate Â*
directly. Â*Simply using a delegate would not accomplish this.

So it is meant for a user to prevent exposing the delegate instance to
the event? So events becomes just an anonymous placeholder for a
delegate.
I don't know what you mean by "anonymous placeholder". They're neither
anonymous nor just a placeholder. They are named, and they have actual
implementation behind them. It's just that, just like a property does, an
event creates an encapsulation of functionality that hides the underlying
implementation from the user code.

It's basically a type of interface or data contract if you will. An event
promises to the user certain semantics -- add and remove -- along with a
specific data type (whatever delegate type is used for the event). That's
_all_ the user is promised, and inside the event implementation, the class
is free to implement it however they like.

Now, just as in C# 3.0 there are automatic properties, events in C# have
an automatic, or default, implementation in which the compiler creates the
add and remove methods for you, as well as a private field for storing the
state of the event.

Unlike the case with automatic properties, for an automatic event the
class declaring the event still needs to be able to distinguish between
the event itself and the field storing the state, because the event itself
can't be read. So it's a _little_ different from a property in that
respect; when the declaring class uses the event name, it gets the field,
but when any other code uses the event name, it gets the event itself.

But other than that, if you understand why properties are useful, you
should also understand why the similar encapsulation an event provides is
useful.

Pete
Oct 28 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Marty McDonald | last post by:
It is still unclear to me why we would use events when delegates seem to do just fine. People say that events make it so the publisher doesn't need to know about the listeners. What does that...
7
by: Rakesh Rajan | last post by:
Hi, I find that when i define a delegate, it gets derived from MulticastDelegate, which provides all funtionality that events would provide (like registering new handlers etc.). Then, apart from...
4
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on...
3
by: Chris | last post by:
Hi, what is the difference between using events and delegates (apart from the syntax) ? have a look at following (working) programs please (you can just copy/paste and build it) : First...
11
by: Nicky Smith | last post by:
Hello, I'm studying a book on VB.net Win apps, and I'm reading a section on events and delegates and raising events. Is it just me, or is this not just subs dressed up as something else? I...
4
by: Tim | last post by:
There are a set of clients who need to be notified of certain events. I have used events and delegates (publisher-Subscriber model) for the notification mechanism. All the clients register with...
30
by: Burkhard | last post by:
Hi, I am new to C# (with long year experience in C++) and I am a bit confused by the language construct of events. What is it I can do with events that I cannot do with delegates? At the moment...
2
by: kristian.freed | last post by:
Hi, I currently work in a project written fully in C# where we make extensive use of delegates and events. We have a model where a "state", an object holding data but not much code but which...
5
by: raylopez99 | last post by:
I understand delegates (static and non-static) and I agree they are very useful, and that the "Forms" used in the Windows .NET API could not work without them. That said, I'm curious as to how...
7
by: Siegfried Heintze | last post by:
I'm studying the book "Microsoft Visual Basic.NET Language Reference" and I would like some clarify the difference between events and delegates. On page 156 I see a WinForms example of timer that...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.