473,802 Members | 1,984 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Questions About Delegates

The following questions are with respect to this delegate declaration:

delegate void MyDelegate(stri ng s);

Question 1:
Why does the following NOT work? Why can't I just create a new instance of
MyDelegate that references zero methods?

MyDelegate d;
d = new MyDelegate();
Question 2:
Given that the following code successfully registers two methods with the
MyDelegate instance...

MyDelegate d = new MyDelegate(MyMe thod)
d += new MyDelegate(MyOt herMethod);

.... why do we have to register the additional method (MyOtherMethod) via a
NEW MyDelegate instance? The above code (d += new MyDelegate...) makes it so
we are adding an instance of a delegate to an instance of a delegate. When
our objective is "simply to register an additional method with a delegate
instance" why can we not simply do something like:

d.Add(MyOtherMe thod); // I know, there is no Add method - but why not?
or
d += MyOtherMethod;

I thought that delegates maintained an internal linked list of "methods to
call" - I would therefore expect a simple .Add() method that lets us add
method references to a delegate instance.
Question 3:
When we want to remove a method reference from a delegate, we still must use
the 'new' keyword, like this:

d -= new MyDelegate(MyMe thod);

Why do we have to use the 'new' keyword when UNregistering a method
reference?

Thanks!
Sep 17 '07 #1
4 1381
On Sep 17, 10:47 am, "Frankie" <A...@B.COMwrot e:
The following questions are with respect to this delegate declaration:

delegate void MyDelegate(stri ng s);

Question 1:
Why does the following NOT work? Why can't I just create a new instance of
MyDelegate that references zero methods?

MyDelegate d;
d = new MyDelegate();
It wouldn't make sense to have a delegate instance that points to
nothing.
Question 2:
Given that the following code successfully registers two methods with the
MyDelegate instance...

MyDelegate d = new MyDelegate(MyMe thod)
d += new MyDelegate(MyOt herMethod);

... why do we have to register the additional method (MyOtherMethod) via a
NEW MyDelegate instance? The above code (d += new MyDelegate...) makes it so
we are adding an instance of a delegate to an instance of a delegate. When
our objective is "simply to register an additional method with a delegate
instance" why can we not simply do something like:

d.Add(MyOtherMe thod); // I know, there is no Add method - but why not?
or
d += MyOtherMethod;

I thought that delegates maintained an internal linked list of "methods to
call" - I would therefore expect a simple .Add() method that lets us add
method references to a delegate instance.
No, you aren't adding another target to the current instance.
Delegates cannot accept additional "registrati ons" after they are
created because they are immutable. The += operator creates a new
delegate instance that is a composite of the current delegates
invocation list plus the new target you want to add.

Perhaps the designers felt there would be confusion because most
(all?) of the Add methods in the BCL effect the current instance. So
having an Add method that behaved like...say...th e String.Replace
method would be weird.
>
Question 3:
When we want to remove a method reference from a delegate, we still must use
the 'new' keyword, like this:

d -= new MyDelegate(MyMe thod);

Why do we have to use the 'new' keyword when UNregistering a method
reference?
I presume the designers wanted the remove operation to be similar,
semantically anyway, to the add operation so that was a natural
choice.

Sep 17 '07 #2
Thanks all. I was missing the fact that delegates are immutable.

Brian and Nicholas questioned my first question...

<< It wouldn't make sense to have a delegate instance that points to
nothing>>
and
<< If you don't give it a method to point to, then what good is the
instance? >>

First, the question was more theoretical in nature.

Second, it is not unusual to create an instance of some object, and then
later give it meaning. Sometimes we want to create object variables in one
location (perhaps at a higher scope), and then set it to something
meaningful later.

-Frankie

"Brian Gideon" <br*********@ya hoo.comwrote in message
news:11******** *************@y 42g2000hsy.goog legroups.com...
On Sep 17, 10:47 am, "Frankie" <A...@B.COMwrot e:
>The following questions are with respect to this delegate declaration:

delegate void MyDelegate(stri ng s);

Question 1:
Why does the following NOT work? Why can't I just create a new instance
of
MyDelegate that references zero methods?

MyDelegate d;
d = new MyDelegate();

It wouldn't make sense to have a delegate instance that points to
nothing.
>Question 2:
Given that the following code successfully registers two methods with the
MyDelegate instance...

MyDelegate d = new MyDelegate(MyMe thod)
d += new MyDelegate(MyOt herMethod);

... why do we have to register the additional method (MyOtherMethod) via
a
NEW MyDelegate instance? The above code (d += new MyDelegate...) makes it
so
we are adding an instance of a delegate to an instance of a delegate.
When
our objective is "simply to register an additional method with a delegate
instance" why can we not simply do something like:

d.Add(MyOtherMe thod); // I know, there is no Add method - but why
not?
or
d += MyOtherMethod;

I thought that delegates maintained an internal linked list of "methods
to
call" - I would therefore expect a simple .Add() method that lets us add
method references to a delegate instance.

No, you aren't adding another target to the current instance.
Delegates cannot accept additional "registrati ons" after they are
created because they are immutable. The += operator creates a new
delegate instance that is a composite of the current delegates
invocation list plus the new target you want to add.

Perhaps the designers felt there would be confusion because most
(all?) of the Add methods in the BCL effect the current instance. So
having an Add method that behaved like...say...th e String.Replace
method would be weird.
>>
Question 3:
When we want to remove a method reference from a delegate, we still must
use
the 'new' keyword, like this:

d -= new MyDelegate(MyMe thod);

Why do we have to use the 'new' keyword when UNregistering a method
reference?

I presume the designers wanted the remove operation to be similar,
semantically anyway, to the add operation so that was a natural
choice.

Sep 17 '07 #3
Frankie wrote:
[...]
Second, it is not unusual to create an instance of some object, and then
later give it meaning. Sometimes we want to create object variables in one
location (perhaps at a higher scope), and then set it to something
meaningful later.
That's true. And typically you'd do that by declaring the variable of
the type of interest, but letting the default initialization of "null"
take place. Then you set the variable to some instance later. It's
quite common to do what you describe; but I can't recall seeing it done
in the _way_ that you expect delegate to do it.

Likewise with the delegate type. You can in fact declare a _variable_
of that type, without setting it to anything. But it doesn't make sense
to have an _instance_ of that type that doesn't refer to anything,
mainly because the semantics of the type imply that if it's non-null you
can execute it.

As Jon said, you can create a simple "nop" instance of a delegate, but
you can't have a delegate instance that refers to nothing. You might as
well just have the delegate variable refer to "null" in that case.

Which is, in fact, how you do it in pretty much any other class. For
example, how would you construct a Form instance that doesn't actually
encapsulate an actual Form?

Pete
Sep 17 '07 #4

"Frankie" <A@B.COMwrote in message
news:O0******** ********@TK2MSF TNGP02.phx.gbl. ..
>
Question 3:
When we want to remove a method reference from a delegate, we still must
use the 'new' keyword, like this:

d -= new MyDelegate(MyMe thod);

Why do we have to use the 'new' keyword when UNregistering a method
reference?
You don't have to use the 'new' keyword to unregister a method reference.
I've done this before:

EventHandler m_handler = new EventHandler(Ha ndleEvent);

this.Click += m_handler;
....
// remove event handler
this.Click -= m_handler;

// which is equivalent to
this.Click -= new EventHandler(Ha ndleEvent);
....

I think that from a semantic point of view, the 'new' syntax didn't make
sense to me. I mean, delegates are reference types, right? So, removing a
'new' instance wouldn't accomplish anything. But, because they are
immutable, reference equality is overriden to behave like value equality (
just like strings ). You could consider the 'new' delegate removal syntax
handy because you don't have to keep a delegate instance around in your
class if you want to attatch, and detatch from an event.

Sep 17 '07 #5

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

Similar topics

6
2293
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...
1
2335
by: Manco | last post by:
1. A delegate is a type-safe, object-oriented function pointer. 2. A delegate declartion is C-sharp, f.e., public delegate void MyDelegate(int); defines a MulticastDelgate which contains a linked-list of delegates that can be added using .Combine method. 3. An event object is an implementation of the Observer design pattern. 4. An event is declared thus:
4
22891
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
3203
by: WStoreyII | last post by:
I have a Collection Class That I am Creating , In This Collection Class I have a default Property Item. My Problem is this I have about twenty different Criterias that can be used as a value in searching for this item. So i figured that i could use overloaded item property's, however it seems that i may not have an overloaded property of the same value type
0
4775
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
2663
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
3424
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
5597
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...
0
10538
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10305
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
10285
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
9115
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 project—planning, coding, testing, and deployment—without 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
7598
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
6838
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5494
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
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
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.