473,788 Members | 2,919 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1541
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(st ring)
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(st ring)
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******** ******@TK2MSFTN GP02.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.netNoS pamMwrote:
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
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...
8
1776
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 sections in both books that try to teach the use of delagates and events, I'm really lost, and to make matters worse, I've written a user-control that fires events for the host form, and this works without delegates!
4
5830
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...
6
2505
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 extremely appropriate (as opposed to other programmatic means or mechanisms) that were NOT related to events and ThreadStarts? Thanks, Jon
2
1222
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 worthy to use in our application. I doubt what's the purpose the delegates?
69
5594
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...
8
273
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 other words that could fill in the blank though. "Or am I _______ as usual?"
3
4849
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 pointers (delegates). I assume I need to use the array< T keyword to allocate an array of delegates, and then initialize the array by setting each array element to the pointers (handles) of the functions I'll be invoking. I've been trying to...
9
3118
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 to store multicast delegates in a hash table, and then fire the delegates one of two ways (after registering/ creating the delegates, etc).
0
9498
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
10370
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
10177
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
10113
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
9969
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
8995
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...
0
5402
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
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.