473,836 Members | 1,615 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Delegates

im having problems trying to understand the delegates in
c#, does anybody know some link where i can find a good
and simple explanation?

thanks
Nov 15 '05
15 3736
news.microsoft. com <di********@dis cussion.microso ft.com> wrote:
Its something .NET should have addressed. An unsecure app message queue.


But that's completely unrelated to whether or not the idea of events is
good or not.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #11
i agree, with caveat below, and you raise a very
reasonable concern-- but also one that i would address
very simply. seems to me that the correct way to enable
reflection would be to change the "add/remove" paradigm
to "add/remove/get". then for instance to do a copy you
would use get followed by a += loop. your accidental
problem below wouldnt happen because there is no "set".
you might not even call the new accessor "get" but rather
a cast of the event to a MulticastDelega te.

now the caveat: the current model actually DOES allow
you to write the accidental errant code exactly as you
just proposed-- provided 2 conditions are met. First,
your errant code must appear in the class which declares
the event rather than in a different class-- admittedly
not a common scenario since it is normally external
objects which register event handlers. Second, the event
must have been declared using the (more common) variable-
declarators form rather than the member-name (accessor)
form.

voila: i kid you not-- try it! if you write the
statement in one class you get a compiler error, in
another class you don't (even though the declaration is
marked "public"). if you declare the event using one
syntax you get a compiler error, using the alternate
syntax you don't. now i bet you didnt know that, and i
bet most programmers don't know that, so i submit that if
you dont agree with me that the event grammar is bogus,
you should at least agree that it is OBSCURE.

back to working with reality the way it is, do you happen
to know who actually designed this into the c# grammar?
are there any discussion threads or anybody who would
remember what they were actually thinking or where they
got their model or inspiration from? i am indeed
curious!!
-----Original Message-----
The concern is more about accidental problems as opposed to maliciousintent. If you could assign directly, you'd be able to write:
appDomain.Doma inLoadEvent = new EventHandler(ro utine);

If somebody was already hooked up to the event, you would have just unhookedthem. Which would be bad.
--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights."wood bee hacker" <al****@digital word.net> wrote in messagenews:02******* *************** ******@phx.gbl. ..
the problem with the event model is that it offers an add- remove syntax which prevents retrieving any delegates
that have been assigned to the event. this means that
you can't retrieve event handlers in reflection, for
instance you can't copy event handlers from one object to another.

according to liberty, this is to prevent objects with
access to the event (Main in liberty's example) from
impersonating the event (Main causing the printing of a
fictitious time on the console). this kind of issue is
silly, of coures main can do all kinds of wierd stuff if it really wants, requiring that main not hijack events
should be a matter of style not language grammar.

btw does anybody know if there is a pre-c# history to the event model that c# simply copied, or is the add/remove
event model novel with c#?

>-----Original Message-----
>would b hacker <al****@digital word.net> wrote:
>> btw his discussion of why events have the accessors

they
>> do is dumb, but that's another story..
>
>What's "dumb" about it? Makes perfect sense to me.
>
>--
>Jon Skeet - <sk***@pobox.co m>
>http://www.pobox.com/~skeet
>If replying to the group, please do not mail me too
>.
>

.

Nov 15 '05 #12
wood bee hacker <al****@digital word.net> wrote:
i agree, with caveat below, and you raise a very
reasonable concern-- but also one that i would address
very simply. seems to me that the correct way to enable
reflection would be to change the "add/remove" paradigm
to "add/remove/get". then for instance to do a copy you
would use get followed by a += loop. your accidental
problem below wouldnt happen because there is no "set".
you might not even call the new accessor "get" but rather
a cast of the event to a MulticastDelega te.
If you want to provide that functionality, I don't believe there's
anything stopping you from doing so - you can write your own code to
store the event handlers, and then provide a way of accessing them.
now the caveat: the current model actually DOES allow
you to write the accidental errant code exactly as you
just proposed-- provided 2 conditions are met. First,
your errant code must appear in the class which declares
the event rather than in a different class-- admittedly
not a common scenario since it is normally external
objects which register event handlers. Second, the event
must have been declared using the (more common) variable-
declarators form rather than the member-name (accessor)
form.

voila: i kid you not-- try it!
No need to, I believe you.
if you write the
statement in one class you get a compiler error, in
another class you don't (even though the declaration is
marked "public").
And that's pretty reasonable, given the intention. I don't think it's
that odd to automatically give the class itself rather more control
over the event.
if you declare the event using one
syntax you get a compiler error, using the alternate
syntax you don't. now i bet you didnt know that, and i
bet most programmers don't know that, so i submit that if
you dont agree with me that the event grammar is bogus,
you should at least agree that it is OBSCURE.
It's obscure, but you won't run into it unless you're trying to do
something that very few people will want or need to do. I don't have
much of a problem with that. I also don't *think* it's guaranteed by
the C# spec - it's due to the way that the MS C# compiler *happens* to
pick the same variable name for the field as for the event (rather than
__eventName as the C# spec example suggests as a possibility). *That*
is a bit of a pity, I agree. (In that people may start relying on it
when they shouldn't.)
back to working with reality the way it is, do you happen
to know who actually designed this into the c# grammar?
are there any discussion threads or anybody who would
remember what they were actually thinking or where they
got their model or inspiration from? i am indeed
curious!!


I don't know of any discussions about it - but then I arrived fairly
late on the C# scene.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #13
thanks jon, especially for the insight about fields v
events!

here's a simple thing i want to do, is there a simple or
standard way to do it? i want to VSDesigner a template
TreeView object and copy it at runtime to a new TreeView
() object. i can copy the properties no problem using
reflection, how do i copy the events?

known but tacky solutions are: manually += the events in
code rather than Designer (yuk), or wrap TreeView and
manually supply the functionality as you mention
previously (awkward, and breaks if TreeView changes).

thanks in advance!

-----Original Message-----
wood bee hacker <al****@digital word.net> wrote:
i agree, with caveat below, and you raise a very
reasonable concern-- but also one that i would address
very simply. seems to me that the correct way to enable reflection would be to change the "add/remove" paradigm to "add/remove/get". then for instance to do a copy you would use get followed by a += loop. your accidental
problem below wouldnt happen because there is no "set". you might not even call the new accessor "get" but rather a cast of the event to a MulticastDelega te.
If you want to provide that functionality, I don't

believe there'sanything stopping you from doing so - you can write your own code tostore the event handlers, and then provide a way of accessing them.
now the caveat: the current model actually DOES allow
you to write the accidental errant code exactly as you
just proposed-- provided 2 conditions are met. First,
your errant code must appear in the class which declares the event rather than in a different class-- admittedly not a common scenario since it is normally external
objects which register event handlers. Second, the event must have been declared using the (more common) variable- declarators form rather than the member-name (accessor) form.

voila: i kid you not-- try it!
No need to, I believe you.
if you write the
statement in one class you get a compiler error, in
another class you don't (even though the declaration is marked "public").


And that's pretty reasonable, given the intention. I

don't think it'sthat odd to automatically give the class itself rather more controlover the event.
if you declare the event using one
syntax you get a compiler error, using the alternate
syntax you don't. now i bet you didnt know that, and i bet most programmers don't know that, so i submit that if you dont agree with me that the event grammar is bogus, you should at least agree that it is OBSCURE.
It's obscure, but you won't run into it unless you're

trying to dosomething that very few people will want or need to do. I don't havemuch of a problem with that. I also don't *think* it's guaranteed bythe C# spec - it's due to the way that the MS C# compiler *happens* topick the same variable name for the field as for the event (rather than__eventName as the C# spec example suggests as a possibility). *That*is a bit of a pity, I agree. (In that people may start relying on itwhen they shouldn't.)
back to working with reality the way it is, do you happen to know who actually designed this into the c# grammar? are there any discussion threads or anybody who would
remember what they were actually thinking or where they got their model or inspiration from? i am indeed
curious!!
I don't know of any discussions about it - but then I

arrived fairlylate on the C# scene.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
.

Nov 15 '05 #14
wood bee hacker <al****@digital word.net> wrote:
thanks jon, especially for the insight about fields v
events!

here's a simple thing i want to do, is there a simple or
standard way to do it? i want to VSDesigner a template
TreeView object and copy it at runtime to a new TreeView
() object. i can copy the properties no problem using
reflection, how do i copy the events?
Well, I'd suggest using Clone, but that doesn't exist for TreeView. Of
course, you could derive from TreeView yourself, and call
Object.Memberwi seClone from there, but then I suspect your event
handlers would be really tied to each other.
known but tacky solutions are: manually += the events in
code rather than Designer (yuk), or wrap TreeView and
manually supply the functionality as you mention
previously (awkward, and breaks if TreeView changes).


I don't know of any other way, to be honest.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #15
--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"wood bee hacker" <al****@digital word.net> wrote in message
news:08******** *************** *****@phx.gbl.. .
i agree, with caveat below, and you raise a very
reasonable concern-- but also one that i would address
very simply. seems to me that the correct way to enable
reflection would be to change the "add/remove" paradigm
to "add/remove/get". then for instance to do a copy you
would use get followed by a += loop. your accidental
problem below wouldnt happen because there is no "set".
you might not even call the new accessor "get" but rather
a cast of the event to a MulticastDelega te.
Can you explain the scenario where you need to do this?

now the caveat: the current model actually DOES allow
you to write the accidental errant code exactly as you
just proposed-- provided 2 conditions are met. First,
your errant code must appear in the class which declares
the event rather than in a different class-- admittedly
not a common scenario since it is normally external
objects which register event handlers. Second, the event
must have been declared using the (more common) variable-
declarators form rather than the member-name (accessor)
form.
A class that defines the event owns the underlying delegate, and can do
whatever it wants to it. It needs full access so that it can do things such
as calling GetInvocationLi st(). This is roughly analogous to properties, in
which the defining class has full control of the backing store.

voila: i kid you not-- try it! if you write the
statement in one class you get a compiler error, in
another class you don't (even though the declaration is
marked "public"). if you declare the event using one
syntax you get a compiler error, using the alternate
syntax you don't. now i bet you didnt know that, and i
bet most programmers don't know that, so i submit that if
you dont agree with me that the event grammar is bogus,
you should at least agree that it is OBSCURE.
If you use the advanced syntax - and it's pretty rare that you would *want*
to do so - you can cause the same problems if you write your code
incorrectly.
back to working with reality the way it is, do you happen
to know who actually designed this into the c# grammar?
are there any discussion threads or anybody who would
remember what they were actually thinking or where they
got their model or inspiration from? i am indeed
curious!!
The feature was designed by the C# language design team, and I was a member
at the time we did events.



-----Original Message-----
The concern is more about accidental problems as opposed

to malicious
intent. If you could assign directly, you'd be able to

write:

appDomain.Doma inLoadEvent = new EventHandler(ro utine);

If somebody was already hooked up to the event, you

would have just unhooked
them. Which would be bad.
--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and

confers no rights.
"wood bee hacker" <al****@digital word.net> wrote in

message
news:02******* *************** ******@phx.gbl. ..
the problem with the event model is that it offers an add- remove syntax which prevents retrieving any delegates
that have been assigned to the event. this means that
you can't retrieve event handlers in reflection, for
instance you can't copy event handlers from one object to another.

according to liberty, this is to prevent objects with
access to the event (Main in liberty's example) from
impersonating the event (Main causing the printing of a
fictitious time on the console). this kind of issue is
silly, of coures main can do all kinds of wierd stuff if it really wants, requiring that main not hijack events
should be a matter of style not language grammar.

btw does anybody know if there is a pre-c# history to the event model that c# simply copied, or is the add/remove
event model novel with c#?
>-----Original Message-----
>would b hacker <al****@digital word.net> wrote:
>> btw his discussion of why events have the accessors
they
>> do is dumb, but that's another story..
>
>What's "dumb" about it? Makes perfect sense to me.
>
>--
>Jon Skeet - <sk***@pobox.co m>
>http://www.pobox.com/~skeet
>If replying to the group, please do not mail me too
>.
>

.

Nov 15 '05 #16

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

Similar topics

6
2294
by: Jeffrey T. Smith | last post by:
Back when the new J2SE1.5 features were announced, there was a JavaLive community chat (http://java.sun.com/developer/community/chat/JavaLive/2003/jl0729.html) in which Neal Gafter explains the Sun stance on lack of support for delegates: .... There are serious semantic problems with trying to add delegates to a language in a consistent way. The main problem is that once you call the delegate, the original class instance is no longer...
3
397
by: Sam | last post by:
I’m just starting to learn delegates. I’m at the very beginning. If I understand correctly, delegates are for when you want to pass a function as a parameter. For example the client provides a custom function to be called in a provider class. My confusion is that you can already achieve this by interfaces and objects without delegates (which have a little more complicated syntax) Here is an example without delegates. class Class1 and...
4
22895
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
4
1881
by: AMDRIT | last post by:
I am trying to understand Delegates and where/when to use them. I can see one potential use of a delegate (on form closing, set the cancel property in the event arguments.) Does anyone have a link to a site that describes delegates using VB.Net in a manner that doesn't require rocket science to become enlightened. TIA
6
2638
by: =?Utf-8?B?Sko=?= | last post by:
I have a logger component that logs to multiple sources, ie textfile, eventlog etc. and I have two methods that depending on where I call up my logger comp. one of them will be called. For ex. if I throw an exception I want to call one method and if I dont, I am just logging some info to eventlog, I will call the other. Now i'm wondering would it make sense to use delegates, one for each method to call methods in my window service? How...
0
4778
by: bharathreddy | last post by:
Delegates Here in this article I will explain about delegates in brief. Some important points about delegates. This article is meant to only those who already know delegates, it will be a quick review not a detailed one. Delegates quite simply are special type of object, a delegate just contains the details of a method. One good way to understanding delegates is by thinking of delegates as something that gives a name to a method...
6
2664
by: =?Utf-8?B?T2xkQ2FEb2c=?= | last post by:
My question is regarding the use of delegates in C#. I see how .Net uses delegates to wire event handlers to events. It’s an object created by a single line of code by the system and that makes perfect sense to me. I understand that there is a lot of code underneath that the system has created that makes it all work, thereby making it pretty efficient for the programmer. Outside of the use of delegates to wire event handlers, you can...
7
3425
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? ...
69
5599
by: raylopez99 | last post by:
They usually don't teach you in most textbooks I've seen that delegates can be used to call class methods from classes that are 'unaware' of the delegate, so long as the class has the same signature for the method (i.e., as below, int Square (int)). Here is an example to show that feature. Note class "UnAwareClass" has its methods Square and Cuber called by a class DelegateClass. This is because these methods in UnAwareClass have the...
9
3120
by: raylopez99 | last post by:
Hello all Im trying to get the below to work and cannot get the format right. Its from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx What it is: Im trying to store multicast delegates in a hash table, and then fire the delegates one of two ways (after registering/ creating the delegates, etc).
0
9820
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9670
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
10548
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
10591
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
10254
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...
0
9374
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7792
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
5826
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4452
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.