473,698 Members | 2,379 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1421
On Tue, 28 Oct 2008 09:57:08 -0700, puzzlecracker <ir*********@gm ail.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...@nn owslpianmk.com>
wrote:
On Tue, 28 Oct 2008 09:57:08 -0700, puzzlecracker <ironsel2...@gm ail.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

"puzzlecrac ker" <ir*********@gm ail.comwrote in message
news:16******** *************** ***********@a29 g2000pra.google groups.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*********@gm ail.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<stri ng, Delegate_dictEv entHandlers = new
Dictionary<stri ng, Delegate>();

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

if (_dictEventHand lers.TryGetValu e(strEventName, out
handlerCur))
{
handlerCur += handler;
}
else
{
handlerCur = null;
}

_dictEventHandl ers[strEventName] = handlerCur;
}

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

if (_dictEventHand lers.TryGetValu e(strEventName, out
handlerCur))
{
handlerCur -= handler;
_dictEventHandl ers[strEventName] = handlerCur;
}
}

public event EventHandler BaseEvent
{
add { _AddEventHandle r("BaseEvent" , value); }
remove { _RemoveEventHan dler("BaseEvent ", value); }
}
}

class Derived : Base
{
public event EventHandler DerivedEvent
{
add { _AddEventHandle r("DerivedEvent ", value); }
remove { _RemoveEventHan dler("DerivedEv ent, 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
1770
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 mean? Why are events better than delegates? Thanks
7
1975
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 being a bit more neater, could there have been any other reason that an 'event' keyword became necessary in C#? Thanks in advance, --
4
22879
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 when to use one over another? If anyone could provide any additional info, your comments, best practices, any good articles, specific examples, etc. Thank you
3
1590
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 program uses delegates, the second events but both do inherently the same :
11
1869
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 mean, for one, delegates point to subs, so when you call a delegate, why not just call the sub dierectly and not bother adding the extra code involved adding the delegate?
4
5828
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 the event publisher and subscribe for the events that they are interested in. When a certain event happens, the subscribers are notified about it. I want the clients to return a value after their callback method is called. If any of the client...
30
3638
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 it seems to me that Microsoft has developed similar functionality via two keywords. I do understand that an event offers better encapsulation as the underlying delegate is private, but is that all ? -- Regards
2
2340
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 fires events when the data changes, is often the central part. Connected to these states are various observers that act on changes in data, by altering the information presented to the user, executing code and so on, each observer with its own...
5
2399
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 many heavy duty pro programmers in this newsgroup have actually used a delegate in their code, say in the last year of coding. By "use" I mean constructed a delegate and using it in an Event Source class and an Event Receiver class. Interfaces...
7
3418
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 uses the "WithEvents" and events. There is another example on page 124 that shows how to use delegates to sort an array. I don't understand the difference between events and delegates. Are they redundant features? How do I decide which to use? ...
0
8675
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8604
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9029
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8897
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8862
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6521
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.