473,225 Members | 1,490 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,225 software developers and data experts.

Don't understand delegates

Tem
I've read every example i could find on the subject and still couldn't
figure out its proper usage.

What's the point of delegates, why can't I just invoke the method
directly???

Can someone please help?

Tem

Jun 27 '08 #1
6 1521
Delegates are pointers to methods. They are a way of having a method as a
variable which can be passed around. They are handy for dependency injection
and things. For example. I have some classes which initialise my business
layer at the start of my application. They take a Delegate to a method like
void ReportStatus(string)
The function call this delegate passing a string which states what they are
currently doing for initialisation. This allows be to change how they report
their information by passing in different methods.
The windows forms app passes in a reference to a method which updates a
label on the splash screen. The command line version passes in a method with
prints to the command line. and potentially a server version could pass one
in which logs to a file/database etc and if i dont want to log at all i can
pass a null delegate
The good thing about this is that the logic for logging is seperated
entirely from the logic for initialisation so they are changeable and
testable independantly.

Does this help you see the usefullness of them?
--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"Tem" wrote:
I've read every example i could find on the subject and still couldn't
figure out its proper usage.

What's the point of delegates, why can't I just invoke the method
directly???

Can someone please help?

Tem

Jun 27 '08 #2
This is effectively how events work. In a normal situation like the below,
you could use an event which is effectively a list of delegates to call when
the event is raised. There is a reason in the below example why it isnt an
event but its not important for this discussion.
--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"Ciaran O''Donnell" wrote:
Delegates are pointers to methods. They are a way of having a method as a
variable which can be passed around. They are handy for dependency injection
and things. For example. I have some classes which initialise my business
layer at the start of my application. They take a Delegate to a method like
void ReportStatus(string)
The function call this delegate passing a string which states what they are
currently doing for initialisation. This allows be to change how they report
their information by passing in different methods.
The windows forms app passes in a reference to a method which updates a
label on the splash screen. The command line version passes in a method with
prints to the command line. and potentially a server version could pass one
in which logs to a file/database etc and if i dont want to log at all i can
pass a null delegate
The good thing about this is that the logic for logging is seperated
entirely from the logic for initialisation so they are changeable and
testable independantly.

Does this help you see the usefullness of them?
--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"Tem" wrote:
I've read every example i could find on the subject and still couldn't
figure out its proper usage.

What's the point of delegates, why can't I just invoke the method
directly???

Can someone please help?

Tem
Jun 27 '08 #3
On Apr 25, 2:48*am, "Tem" <tem1...@yahoo.comwrote:
I've read every example i could find on the subject and still couldn't
figure out its proper usage.

What's the point of delegates, why can't I just invoke the method
directly???
Because maybe you do not know which exact method to call. Or maybe the
exact method to call change dynamically.

One way of think of it as if your class is incomplete and is the code
using it who is going to complete it.
Jun 27 '08 #4
Ignacio points out the primary reason: You are not sure what you are calling
until runtime.

Delegates are aslo useful for event handlers, when you only want a specific
bit of code called in a certain instance.

Another reason to delegate is callbacks, which cannot be coded directly as
method calls. I actually restated reason #2, only in different language, and
reason #1, at least in some instances. :-)

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://gregorybeamer.spaces.live.com/lists/feed.rss

or just read it:
http://gregorybeamer.spaces.live.com/

*************************************************
| Think outside the box!
|
*************************************************
"Tem" <te*****@yahoo.comwrote in message
news:eR**************@TK2MSFTNGP02.phx.gbl...
I've read every example i could find on the subject and still couldn't
figure out its proper usage.

What's the point of delegates, why can't I just invoke the method
directly???

Can someone please help?

Tem

Jun 27 '08 #5
On Fri, 25 Apr 2008 08:09:18 -0700, Cowboy (Gregory A. Beamer)
<No************@comcast.netNoSpamMwrote:
Ignacio points out the primary reason: You are not sure what you are
calling
until runtime.
Careful with the "until runtime". _Some_ code usually knows what's going
to be called at compile time. It's just that the _calling_ code doesn't
know until runtime.

With that in mind, I'd say that technically speaking, all uses of
delegates fall into this category. For example...
Delegates are aslo useful for event handlers, when you only want a
specific
bit of code called in a certain instance.
But the reason they are used for event handlers is that at compile time,
the implementer of the event doesn't know what code will be called. The
..NET Forms classes are a classic example of this. Microsoft can't
possibly know what your own code would be when they provide an event. So
using a delegate allows other code to provide the reference to the method
to be called, well after the point at which Microsoft's code was compiled.
Another reason to delegate is callbacks, which cannot be coded directly
as
method calls.
That's not strictly speaking correct, depending on what you mean by "as
method calls". Java doesn't have any idea like delegates, and yet it can
implement the same sort of behavior. It uses interfaces instead. And
those are coded directly as method calls (i.e. a method defined in an
interface implemented by whichever class wants to provide the callback).
This could be done in .NET, and in fact for more elaborate APIs is in fact
used quite a lot.

But regardless, that's still a subset of the general "you don't know at
compile time the exact method that will be called".

I prefer delegates, and I feel that for single-method situations they are
way more convenient than having to create a whole interface and then
implement it in each class that wants to provide a method to call at
specific times (whether to support events, i/o callbacks, whatever). But
you don't _have_ to have delegates to allow for callbacks that aren't
known at compile time.

Pete
Jun 27 '08 #6
Tem... You can use delegates when you need "runtime polymorphic"
behavior.

Runtime polymorphism involves programming to a type, such that the
implementation details can be different and are discoverable at runtime.
When
programming to a type, the caller does not know the class of the object,
only
that the object implements the type of interest.

http://www.geocities.com/jeff_louie/OOP/oop37.htm
http://www.geocities.com/jeff_louie/OOP/oop31.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Jun 27 '08 #7

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

Similar topics

6
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...
8
by: Nicky Smith | last post by:
Hello, I'm reading Mike Gunderloy's Mcad Vb.net book, and I've also read the MS press Mcad book for the same topic ".. Windows based applications with VB.net" for exam 70-306. In the...
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...
6
by: Jon Davis | last post by:
I've used delegates fairly heavily for several years in C# for event handling and for starting threads. Does anyone have any real-world scenarios where delegates were both extremely useful and...
2
by: hangaround | last post by:
I used delegates recently, It seemed the delegates was like function_call very much, and we couldn't use delegates to mimic the system events( ex, button_click), so didn't think the delegates...
69
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...
8
by: Bill Butler | last post by:
"raylopez99" <raylopez99@yahoo.comwrote in message news:bd59f62a-5b54-49e8-9872-ed9aef676049@t54g2000hsg.googlegroups.com... <snip> I don't think "right" is the correct word. There are many...
3
by: David K in San Jose | last post by:
I'm using managed (CLR) C++ in VS2005 to create a Windows app that contains a form named "MyForm". In the code for that form I'm trying to invoke some static functions by using an array of function...
9
by: raylopez99 | last post by:
Hello alló Iím trying to get the below to work and cannot get the format right. Itís from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx What it is: Iím trying...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

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.