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

Home Posts Topics Members FAQ

When to use Delegates

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 would I go about coding
it? Or should I not even bother and just instantiate the logger class and
call the methods when needed?
Jun 26 '07 #1
6 2635
On Tue, 26 Jun 2007 12:48:00 -0700, JJ <JJ@discussions .microsoft.com>
wrote:
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 would I go about
coding
it? Or should I not even bother and just instantiate the logger class and
call the methods when needed?
From your description, I don't see anything that clearly indicates a need
for delegates. It depends on how you would use the delegate. If you are
envisioning a design in which one of two delegates is chosen from
depending on the situation (exception or event logging), then it seems to
me that you might as well just call the method you need to be called. On
the other hand, if you are envisioning a design in which you have a single
delegate, initialized to one of two values depending on the situation,
then perhaps a delegate does make sense.

It just depends, and I don't see enough information in your post to be
able to determine what you intend.

More generally...

If you can accomplish the same exact behavior without using delegates,
then why would you use delegates?

Conversely, if you cannot accomplish the same exact behavior without using
delegates, then why would you attempt to do so?

To me, these are interesting questions to ask yourself when you are
thinking about the design.

It seems to me that delegates are useful in a particular type of
situation: you want to be able to specify at run-time a method to call,
but don't have a situation that lends itself to creating an abstract class
that clients can use to provide derived versions of at run-time. If the
code doing the calling will always call the same method, and that method
can be included at compile time, then there's no need for either.

As an example of using an abstract class, many of the logging type
features in .NET use something that derives from TextReader, usually
taking a StringReader or StreamReader instance as appropriate. No need
for delegates there: each derived class has specific functionality that is
mapped to the general-purpose methods specified in TextReader. By
implementing the derived class (or in this case, using a built-in
implemented derived class) and providing that as the base class, any code
that needs to call different methods depending on context can do so
without know specifically what code it needs to call.

Events are .NET's classic example of the use of delegates (though by no
means the only example). At run-time you have a situation in which one
class wants to be callable by another class, but it doesn't make sense to
derive that one class from some specific abstract class.

You could accomplish similar effects by using an interface, but if you've
got a class that will have dozens of different event handlers, all of
which are subscribed to different kinds of events, the list of interfaces
would get out of hand, and it would be sort of silly to have dozens of
interfaces, all of which have just one method in them. Here, a delegate
works nicely, as the method itself can be implemented in any class you
like, without worrying about inheritance structures, and any class can
implement as many delegates as needed without creating a lengthy,
confusing inheritance list (acknowledging of course that in C#, there's
really only one class that's inherited at most...interfac es are only sort
of like inheriting a purely abstract class).

So, that's the general description. You can either look at that and try
to apply it to your own situation, or you can clarify what your own
situation actually is, so that others can provide better insight as to
whether a delegate seems appropriate or not.

Pete
Jun 26 '07 #2
JJ <JJ@discussions .microsoft.comw rote:
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 would I go about coding
it? Or should I not even bother and just instantiate the logger class and
call the methods when needed?
I'd go with the non-delegate approach to start with - I can't
immediately see where the delegates would make life easier. (I'm not
saying they're not useful in general, just that I can't see the benefit
here.)

--
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
Jun 26 '07 #3
Hi Jon,

What *would* be a scenario or general guidelines where delegates would make
life easier. Just looking for broad guidance (no particualar scenario in
mind).

Thanks.
Jun 27 '07 #4
On Tue, 26 Jun 2007 17:34:41 -0700, Bob Johnson <A@B.COMwrote :
What *would* be a scenario or general guidelines where delegates would
make
life easier. Just looking for broad guidance (no particualar scenario in
mind).
I described that briefly in my post, in reply to your original question.
Was there something about that example that didn't make sense to you, or
didn't seem applicable?

Generally speaking, delegates are very much like function pointers in C.
But because of the "event" type in C#, they are much more integral to the
use of the language. The .NET Framework uses events extensively to allow
one class to extend another class without having to derive from it, or to
provide inter-class communication, and without delegates events just don't
work. Delegates are also used in a variety of callback scenarios:
predicates used for searching collections, methods intended as entry
points for threads, callback routines for asynchronous i/o, etc.

Pretty much any time you have a situation in which you want a method to be
called by some code that does not know in advance which method will be
called, and in which there's no natural overridable class that can provide
a virtual method to do that, that's the sort of situation you'd use a
delegate in.

Pete
Jun 27 '07 #5
RE:
<< I described that briefly in my post, in reply to your original question
>>
I'm not the person who posted the original question in this thread. Thanks
for offering further clarification anyway.


Jun 27 '07 #6
On Wed, 27 Jun 2007 09:04:05 -0700, Bob Johnson <A@B.COMwrote :
I'm not the person who posted the original question in this thread.
Thanks
for offering further clarification anyway.
Ah...my mistake. Sorry for any confusion.
Jun 27 '07 #7

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

Similar topics

2
1581
by: Marcos Stefanakopolus | last post by:
In C# is there any way to use the concept of delegates to have multiple implementations of a particular block of code, so that you can choose between them without the overhead of possibly expensive if() or switch() logic, and without the overhead of a function call? As an example, consider the task of resizing a bitmap from size X1,Y1 to size X2,Y2 (may be shrunk or expanded, may or may not maintain aspect ratio). Code that handles the...
4
1735
by: DKode | last post by:
Hello, I have a question about delegates and events I have a basic understanding of each, but in the apps I'm building I'm never needing to use these tools. I'm wondering when and where you should use these features. I am assuming that they are used in your presentation layer but perhaps I am sorely wrong. thank you
6
2503
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
1221
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?
22
16940
by: dvestal | last post by:
Suppose I have this: class C { public delegate void MyEventHandler(); public event MyEventHandler MyEvent; public void foo() { MyEvent(); // NullReferenceException? } }
6
2661
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
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
8831
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
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...
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...
1
6796
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
6076
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();...
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.