473,401 Members | 2,146 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,401 software developers and data experts.

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 2597
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...interfaces 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.comwrote:
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.com>
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
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...
4
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...
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...
22
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
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...
7
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...
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...
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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...

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.