473,748 Members | 2,274 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The practical use of delegates

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 create your
own delegates to make a call to a method, which according to some, makes
delegates perfect for implementing callbacks. My question is this:

In a lot situations, I can create less code by calling that function or
method directly rather than using delegates (for static or instance methods).
Are delegates good all the time, some of the time, or when? Am I missing
something? Why are so many so high on using delegates as much as they can?
Is there a security issue that makes delegates better than a direct call?

I just don’t have enough experience yet to figure this one out yet. Any
help will be appreciated. Thanks in advance for your help.

--
Scott
Sep 24 '07 #1
6 2661
Scott,

Well, the callback is a perfect example. You might know the method that
needs to be called at a certain point in the procedure, but that would tie
that code to that specific procedure, and not make the code very flexible.

Great examples of this are callbacks in Sockets when data is read, data
base connections when commands are executed, etc, etc. Delegates are a
great way to indicate the action that should be taken when an operation is
complete.

Granted, you could use interface implementations (create a specialized
interface which has a method with the signature you need for the callback)
but that can be a little bit of a hassle if you want to keep your code more
clean/concise (as the implementation would typically be in another class,
but then you have to have that other class call back into the calling class
to do the work). This is one of the things I didn't like in the early days
of Java (we are talking 10 years ago).

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"OldCaDog" <sb*******@comm unity.nospamwro te in message
news:62******** *************** ***********@mic rosoft.com...
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 create
your
own delegates to make a call to a method, which according to some, makes
delegates perfect for implementing callbacks. My question is this:

In a lot situations, I can create less code by calling that function or
method directly rather than using delegates (for static or instance
methods).
Are delegates good all the time, some of the time, or when? Am I missing
something? Why are so many so high on using delegates as much as they
can?
Is there a security issue that makes delegates better than a direct call?

I just don't have enough experience yet to figure this one out yet. Any
help will be appreciated. Thanks in advance for your help.

--
Scott

Sep 24 '07 #2

One way to consider the use of delegates is like this
"Delegates are kinda Microsoft's "built in" Observer Pattern".

See
http://www.dofactory.com/Patterns/PatternObserver.aspx

Instead of doing the Observer pattern , with an interface like IObserver,
you can use delegates to handle this.
So anywhere that the Observer pattern would make sense, you can use
delegates.


"OldCaDog" <sb*******@comm unity.nospamwro te in message
news:62******** *************** ***********@mic rosoft.com...
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 create
your
own delegates to make a call to a method, which according to some, makes
delegates perfect for implementing callbacks. My question is this:

In a lot situations, I can create less code by calling that function or
method directly rather than using delegates (for static or instance
methods).
Are delegates good all the time, some of the time, or when? Am I missing
something? Why are so many so high on using delegates as much as they
can?
Is there a security issue that makes delegates better than a direct call?

I just don't have enough experience yet to figure this one out yet. Any
help will be appreciated. Thanks in advance for your help.

--
Scott

Sep 24 '07 #3
Hi,

"OldCaDog" <sb*******@comm unity.nospamwro te in message
news:62******** *************** ***********@mic rosoft.com...
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 create
your
own delegates to make a call to a method, which according to some, makes
delegates perfect for implementing callbacks. My question is this:

In a lot situations, I can create less code by calling that function or
method directly rather than using delegates (for static or instance
methods).
You are right, but what if you do not know the actual method you will need
to call?
A callback is an excellent example of this.

In this case you need a feature that let you dynamically select which method
to call. This feature are the delegates.
Sep 24 '07 #4
OldCaDog <sb*******@comm unity.nospamwro te:

<snip>
In a lot situations, I can create less code by calling that function or
method directly rather than using delegates (for static or instance methods).
And when you know exactly what to call at the point you want to make
the call, you might as well call the method directly.

Delegates are specifically for situations where you want the action to
take place at one point of the code, but you want to be able to control
what happens from another point of code.

In C# 1, delegates are relatively rarely used outside event handlers
and callbacks.

In C# 2 there are more uses (e.g. List.ConvertAll etc) and various
language enhancements make them easier to use.

In C# 3 there's *far* more scope to use delegates due to LINQ etc - and
lambda expressions make them really, really concise.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Sep 24 '07 #5
Thank you all for taking the time to comment, I really appreciate it! You've
all given me much more to consider and investigate, thanks again.
--
Scott
"Jon Skeet [C# MVP]" wrote:
OldCaDog <sb*******@comm unity.nospamwro te:

<snip>
In a lot situations, I can create less code by calling that function or
method directly rather than using delegates (for static or instance methods).

And when you know exactly what to call at the point you want to make
the call, you might as well call the method directly.

Delegates are specifically for situations where you want the action to
take place at one point of the code, but you want to be able to control
what happens from another point of code.

In C# 1, delegates are relatively rarely used outside event handlers
and callbacks.

In C# 2 there are more uses (e.g. List.ConvertAll etc) and various
language enhancements make them easier to use.

In C# 3 there's *far* more scope to use delegates due to LINQ etc - and
lambda expressions make them really, really concise.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Sep 24 '07 #6

"OldCaDog" <sb*******@comm unity.nospamwro te in message
news:62******** *************** ***********@mic rosoft.com...
In a lot situations, I can create less code by calling that function or
method directly rather than using delegates (for static or instance
methods).
Are delegates good all the time, some of the time, or when?
This thread is mostly about when to use delegates.
Let me turn it on its head, becuase you seem to have heard
that delegates are good, and that you should use them.

But I'd like to stress this, that has not yet to mentioned yet in this
thread.
But you seem to have figured it out. :)

- If you know the method (on a known instance) of a specific class to
call...
- You should call it directly!

By using a delegate to call a known method,
you are just not only engaging in total overkill, it is bad code!
As your code would suggest the call is dynamic and could change,
when it is not.

String.Format(" Only exception is if you really hate
your {0} maintainers {1}, "future", ", that might be yourself 2 years
later");

..NET Is Not Java :)
- Michael Starberg
Sep 26 '07 #7

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

Similar topics

6
2289
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
22886
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
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
6
2635
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
4772
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...
7
3420
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
5584
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
3116
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
8991
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
9552
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
9376
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
9326
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
9249
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
8245
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
4877
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.