473,785 Members | 2,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help understanding delegates?

I'd like to better understand how the following code works. I've posted
questions below.

namespace Something.Somet hing1
{
using System;

public delegate void Test1();
public delegate void Test2(ink k);

public class A
{
public static void Log1 (int l)
{
Console.WriteLi ne(":{0}",l);
}

public void Log2 (int l)
{
Console.WriteLi ne("#{0}",l);
}
}

public class Class1
{
public static void Main()
{
A a = new A();
Test2 t0 = new Test2(A.Log1); //use static method
Test2 t1 = new Test2(a.Log2); //use instance method

t0 += t1; t0(0);
t0 -= t1; t0(1);
}
}
}

This will print ":0 #0 :1". How does Log1 print 0 when no param is passed
to it and "l" is not initialized to 0?

What are the differences in the static and instance method calls via
delegates?

This line t0 -= t1; t0(1); removes those methods from the delegate
collection correct? How is the output affected if that line does not
exists?

Also, if I'm using the IE object and have three successive page loads, will
each of the following events respectively fire after each page load rather
than all three always firing after each page load? In other words, after
the first page load completes, onIEDocComplete 1 fires. After the second
page load completes, onIEDocComplete 2 fires. After the third page load
completes, onIEDocComplete 3 fires.

IE_Inst.Documen tComplete += new
SHDocVw.DWebBro wserEvents2_Doc umentCompleteEv entHandler(this .onIEDocComplet e1);

IE_Inst.Documen tComplete += new
SHDocVw.DWebBro wserEvents2_Doc umentCompleteEv entHandler(this .onIEDocComplet e2);

IE_Inst.Documen tComplete += new
SHDocVw.DWebBro wserEvents2_Doc umentCompleteEv entHandler(this .onIEDocComplet e3);

Thanks,
Brett
Nov 17 '05
29 1893

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
Brett <no@spam.com> wrote:
> What do you mean by "get away with using a collection"?


Perhaps it isn't a collection but just a list, as you have mentioned.


The delegate itself isn't a list - it encapsulates a list of
invocations, but it isn't a list in itself.

When you say that you "still get away with using a collection in this
case" what exactly do you mean?
Probably just do a GetType() to determine it.


I don't see how that would help. Could you give an example of what you
mean?


I don't have an example. Was just trying to get a solid definition of what
this structure is that holds a list of events. First it was something that
behaved like a collection, then it was a list. Then not a list but
something encapsulating a list. One of us is very confused but I'm backing
off now. ; )

Thanks,
Brett
Nov 17 '05 #21
Brett <no@spam.com> wrote:
I don't see how that would help. Could you give an example of what you
mean?


I don't have an example. Was just trying to get a solid definition of what
this structure is that holds a list of events. First it was something that
behaved like a collection, then it was a list. Then not a list but
something encapsulating a list. One of us is very confused but I'm backing
off now. ; )


Basically, it contains a list. It's immutable, so you can't change the
list itself, only create a new delegate with a different list
containing the first list. You can't use it as a general purpose
collection, as it can only hold delegates.

The things you've said that confuse me most are:

1) That collections in C# aren't ordered
2) That you've used delegates as collections with no trouble

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

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Brett <no@spam.com> wrote:
> I don't see how that would help. Could you give an example of what you
> mean?
I don't have an example. Was just trying to get a solid definition of
what
this structure is that holds a list of events. First it was something
that
behaved like a collection, then it was a list. Then not a list but
something encapsulating a list. One of us is very confused but I'm
backing
off now. ; )


Basically, it contains a list. It's immutable, so you can't change the
list itself, only create a new delegate with a different list
containing the first list. You can't use it as a general purpose
collection, as it can only hold delegates.

The things you've said that confuse me most are:

1) That collections in C# aren't ordered

My fault.
2) That you've used delegates as collections with no trouble I thought they were collections. I've read they were in some of the online
examples I've seen. That's how they are described. That's not a global
description of course. Perhaps this exchange with Mattias further up in
the thread did me in. You see it hits both of your questions.
[>So is a delegate basically a collection of method pointers that when
called,executes all methods in the collection in the order they were added to the
collection?


Correct, except that I believe the order they are called in is
undefined and implementation dependent.]
Nov 17 '05 #23
In message <#5************ **@TK2MSFTNGP10 .phx.gbl>, Brett <no@spam.com>
writes

2) That you've used delegates as collections with no trouble

I thought they were collections. I've read they were in some of the online
examples I've seen. That's how they are described. That's not a global
description of course.


I think this is just a case of terminology. It's quite common to use
"collection " to describe any container which can manage a number of
contained objects. I think Jon is using it in a stricter .NET specific
sense to mean "implements ICollection". I've got lots of classes
implementing IEnumerable which I would casually describe as
"collection s", but by Jon's definition, they aren't.

--
Steve Walker
Nov 17 '05 #24

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Brett <no@spam.com> wrote:
> I don't see how that would help. Could you give an example of what you
> mean?


I don't have an example. Was just trying to get a solid definition of
what
this structure is that holds a list of events. First it was something
that
behaved like a collection, then it was a list. Then not a list but
something encapsulating a list. One of us is very confused but I'm
backing
off now. ; )


Basically, it contains a list. It's immutable, so you can't change the
list itself, only create a new delegate with a different list
containing the first list. You can't use it as a general purpose
collection, as it can only hold delegates.

The things you've said that confuse me most are:

1) That collections in C# aren't ordered
2) That you've used delegates as collections with no trouble

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


While we're on the subject,. how can I removed all events I've delegated?
For example:

IE_Inst.Documen tComplete -= new
SHDocVw.DWebBro wserEvents2_Doc umentCompleteEv entHandler(this .onIEDocComplet eGetMessages);

and at some later point clear out
IE_Inst.Documen tComplete

so that no event fires based on the page load complete.

Thanks,
Brett
Nov 17 '05 #25
Brett <no@spam.com> wrote:
While we're on the subject,. how can I removed all events I've delegated?
For example:

IE_Inst.Documen tComplete -= new
SHDocVw.DWebBro wserEvents2_Doc umentCompleteEv entHandler(this .onIEDocComplet eGetMessages);

and at some later point clear out
IE_Inst.Documen tComplete

so that no event fires based on the page load complete.


You can only remove specific handlers - so if you know what you've
added, you can remove them again - but you can't just clear out
everything.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #26
mdb
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in
news:MP******** *************** *@msnews.micros oft.com:
You can only remove specific handlers - so if you know what you've
added, you can remove them again - but you can't just clear out
everything.


I think you would be able to iterate through the list of delegates (with
GetInvocationLi st) and remove each one. You probably can even tell whether
its something you've added (versus other classes) with the .Target and/or
..Method properties. Whether you can distinguish between two objects of the
same class with different events might be a bit more difficult, though.

-mdb
Nov 17 '05 #27
mdb <m_b_r_a_y@c_t_ i_u_s_a__d0t__c om> wrote:
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in
news:MP******** *************** *@msnews.micros oft.com:
You can only remove specific handlers - so if you know what you've
added, you can remove them again - but you can't just clear out
everything.


I think you would be able to iterate through the list of delegates (with
GetInvocationLi st) and remove each one. You probably can even tell whether
its something you've added (versus other classes) with the .Target and/or
.Method properties. Whether you can distinguish between two objects of the
same class with different events might be a bit more difficult, though.


You can do that if you have access to the delegate - but if you only
have access to the *event*, you can't get the invocation list, only add
to it and remove from it.

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

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
mdb <m_b_r_a_y@c_t_ i_u_s_a__d0t__c om> wrote:
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in
news:MP******** *************** *@msnews.micros oft.com:
> You can only remove specific handlers - so if you know what you've
> added, you can remove them again - but you can't just clear out
> everything.


I think you would be able to iterate through the list of delegates (with
GetInvocationLi st) and remove each one. You probably can even tell
whether
its something you've added (versus other classes) with the .Target and/or
.Method properties. Whether you can distinguish between two objects of
the
same class with different events might be a bit more difficult, though.


You can do that if you have access to the delegate - but if you only
have access to the *event*, you can't get the invocation list, only add
to it and remove from it.


Using the example in my initial post, say I add two events to the deletgate
t0. Can I use a foreach loop to get at items stored in the t0 delegate
type?

Now, it isn't necessary that I implement IEnurmerable to use a for each
loop? I ask that question because every time I have used a for each loop, I
haven't implemented IEnumerable. However, from the docs:
[IEnumerable must be implemented to support the ForEach semantics of
Microsoft Visual Basic. COM classes that allow enumerators also implement
this interface.]

If the above is true, then t0 is a collection because IEnumerable is in the
System.Collecti ons namespace.

Brett
Nov 17 '05 #29
"Brett" <no@spam.net> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message [Snip]
You can do that if you have access to the delegate - but if you only
have access to the *event*, you can't get the invocation list, only add
to it and remove from it.


Using the example in my initial post, say I add two events to the
deletgate t0. Can I use a foreach loop to get at items stored in the t0
delegate type?


IF you have access to the delegate object itself you can foreach through
Delegate.GetInv ocationList which is an array. Arrays implement IList which
inherits from IEnumerable via ICollection.
Now, it isn't necessary that I implement IEnurmerable to use a for each
loop? I ask that question because every time I have used a for each loop,
I haven't implemented IEnumerable. However, from the docs:
[IEnumerable must be implemented to support the ForEach semantics of
Microsoft Visual Basic. COM classes that allow enumerators also implement
this interface.]
The object you are enumerating on must implement IEnumerable (the one in the
"in" part of your foreach).
If the above is true, then t0 is a collection because IEnumerable is in
the System.Collecti ons namespace.
Sorry, wrong. DictionaryEntry , Comparer, and IHashCodeProvid er are all in
the System.Collecti ons namespace and are not collections. Being in the
namespace does not imply that they ARE collections, merely that they are
related to collections in some way. You're confusing location with identity.
Just to reinforce my point, t0.GetInvocatio nList returns an array which IS a
collection (since it implements ICollection), but Array resides in the
System namespace.
Brett

Nov 17 '05 #30

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

Similar topics

12
2954
by: serge calderara | last post by:
Dear all, I have an application which is suppose to start another executable process. As soon as that process is running, I need to retrive its handle. The problem of the particular process I am starting is that it has a welcome window first which gets displayed and then the real windows after a while,in other words it means that the process name is the same, but the handle I need to retrive is the one from the final window and not the...
22
4071
by: Jeff Louie | last post by:
Well I wonder if my old brain can handle threading. Dose this code look reasonable. Regards, Jeff using System; using System.Diagnostics; using System.IO; using System.Threading;
4
1876
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
2
1093
by: RSH | last post by:
I have been looking at delegates lately. I have seen several articles explaining them but I'm having a hard time understanding why I would use a delegate over a traditional function or sub. Could someone please help me understand why i would use a delegate in day to day use, over a function or sub? Thank you for your time! Ron
0
1094
by: Siegfried Heintze | last post by:
I'm practicing for the C# brain bench test by reviewing how delegates work. (Delegates are easy to to with visual studio because you normally use the delegates that some API as already defined. I'm worried they are going to make me do my own delegates from scratch.) I see that line 33 of Default.aspx is indeed executing when I single step with the debugger. As you can see (on lines of 17 and 18 of propertyDemo.cs I have set up a delegate...
13
1972
by: Praveen | last post by:
trying to learn plymorphism. My sample is public class Class1 { public static void Main(string args) { Cls1 x = new Cls1(); Cls2 y = new Cls2(); Cls3 y = new Cls3();
5
1949
by: sajin | last post by:
Hi All.. We are using VB .Net 2005 for implementing an API. API needs to generate events. For this client wants us to use Windows Callback (delegate implementation). The intention of using Windows Callback is to generalise our API so that it can be compatible with any other language e.g. C++. Using normal delegates will not help us since delegates is a VB.Net feature and any other language cant make a use of it. Could please
4
1298
by: Miro | last post by:
I am trying to understand delegates and I think I do understand them ... just hoping if someone can tell me im on the right track. So far what I have read is that a Delegate is an Asynchronus call to a method or function or whatever... So basically you create an object that references the address of the meathod. By calling this delegate - you get a 'return' right away so your code can continue and the delegate runs in a different...
2
10049
by: hcaptech | last post by:
This is my Test.can you help me ? 1.Which of the following statement about C# varialble is incorrect ? A.A variable is a computer memory location identified by a unique name B.A variable's name is used to access and read the value stored in it C.A variable is allocated or deallocated in memory during runtime D.A variable can be initialized at the time of its creation or later 2. The.……types feature facilitates the definition of classes...
0
9645
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
9480
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
10325
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
10147
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...
0
9950
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
8972
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
7499
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
6739
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.