473,545 Members | 1,310 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proper use of delegates.

Since we are currently on the subject of multi-threading in a different
thread, I have a question about delegates.

When I use delegates, I just create one for each different parameter set
that I need.

For example:

delegate void callBackString( string d_string);

delegate void callBackStringA rray(string[] d_string);

delegate void callBackInt(int d_int);

delegate void callBackSB(stri ng d_string, bool d_bool);

....And then I just reuse them when and where I need them.

Is this the proper way to use delegates?

I'm highly interested in the most efficient way if this isn't it.

Thanks

--
Roger Frost
"Logic Is Syntax Independent"

Feb 22 '08 #1
10 2508
Generics - but it is already done for you: consider Action<T>?
i.e. Action<string>, Action<string[]and Action<intetc match your first 3
examples

..NET 3.5 introduces multi-paramater variants:
Action<string,b oolmatches your last example

If the delegate should return a value, then Func<...is also available -
i.e.
"int Foo(string arg)" would match Func<string,int >

Marc
Feb 22 '08 #2
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
Roger Frost <fr*****@hotmai l.comwrote:
>>
When I use delegates, I just create one for each different parameter set
that I need.

For example:

delegate void callBackString( string d_string);
...And then I just reuse them when and where I need them.

Is this the proper way to use delegates?

I'm highly interested in the most efficient way if this isn't it.

1) You're declaring a type, so use the normal convention for type
names: Pascal case.
Conventions are something that I struggle with and hope to get better at.
When it is just me writing programs, it's not a problem, but I know that I
need to learn the standards...and I appreciate having my mistakes pointed
out.
>
2) If you're using .NET 3.5 you can use the built-in Action<...>
delegates; your delegates above are equivalent to

Action<string>
Action<string[]>
Action<int>
Action<string,b ool>
Yup .NET 3.5, I will optimize my code for this.

Thanks!

Feb 22 '08 #3
On Thu, 21 Feb 2008 23:22:22 -0800, Roger Frost <fr*****@hotmai l.com>
wrote:
Since we are currently on the subject of multi-threading in a different
thread, I have a question about delegates.

When I use delegates, I just create one for each different parameter set
that I need.

[...]
...And then I just reuse them when and where I need them.

Is this the proper way to use delegates?
Well, for single-parameter delegates that return void, you could just use
the generic Action<Tdelegat e. So, for example, where you'd declare and
use "delegate void callBackString( string d_string)", you'd skip the
declaration and just use "Action<string> " instead where you would have
used "callBackString " as the type. There's also a no-parameter delegate
named Action. Non-generic, obviously.

If you're using .NET 3.5, they've added two, three, and four-parameter
versions of the same generic type. If you need more than four parameters,
then you might consider declaring a single generic delegate type for each
parameter count you need that you reuse as necessary, rather than making a
new one for each more-than-four-parameter action you have.

For example:

delegate void Action<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4
t4, T5 t5);

Of course, if you've got more than four parameters for an action, you may
have other issues. But at least you can avoid making all those delegate
types. :)

If you're not using .NET 3.5, then you could of course declare the two-,
three-, and four-parameter Action delegate types yourself, as with the
five-parameter example above (except with fewer parameters, of course :) ).

Pete
Feb 22 '08 #4
Thanks to everyone for the help...here is what I have now:

private void populateListVie ws(string[] fileList)
{//Addes the file(s) to the correct ListView Queues.

//Handle calls from a different thread.
if (InvokeRequired )
{//Caller is on a different thread.

//Create a new delegate.
Action<string[]cb = new
Action<string[]>(populateListV iews);

//Invoke the delegate on the owner thread.
Invoke(cb, new object[] { fileList });
}
else
{//Caller is on this thread.
//The good stuff.
}

Is this the Proper use of delegates in .NET 3.5?

If so, can I get a brief run down of what I am gaining over:

delegate void CallBackStringA rray(string[] d_string);

[...]

CallBackString cb = new CallBackString( populateListVie ws);

Invoke(cb, new object[] { fileList });
While we are here, how are my conventions in these examples?

"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Thu, 21 Feb 2008 23:22:22 -0800, Roger Frost <fr*****@hotmai l.com>
wrote:
>Since we are currently on the subject of multi-threading in a different
thread, I have a question about delegates.

When I use delegates, I just create one for each different parameter set
that I need.

[...]
...And then I just reuse them when and where I need them.

Is this the proper way to use delegates?

Well, for single-parameter delegates that return void, you could just use
the generic Action<Tdelegat e. So, for example, where you'd declare and
use "delegate void callBackString( string d_string)", you'd skip the
declaration and just use "Action<string> " instead where you would have
used "callBackString " as the type. There's also a no-parameter delegate
named Action. Non-generic, obviously.

If you're using .NET 3.5, they've added two, three, and four-parameter
versions of the same generic type. If you need more than four parameters,
then you might consider declaring a single generic delegate type for each
parameter count you need that you reuse as necessary, rather than making a
new one for each more-than-four-parameter action you have.

For example:

delegate void Action<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4
t4, T5 t5);

Of course, if you've got more than four parameters for an action, you may
have other issues. But at least you can avoid making all those delegate
types. :)

If you're not using .NET 3.5, then you could of course declare the two-,
three-, and four-parameter Action delegate types yourself, as with the
five-parameter example above (except with fewer parameters, of course
:) ).

Pete
Feb 22 '08 #5
Oops, how about...
Is this the Proper use of delegates in .NET 3.5?

If so, can I get a brief run down of what I am gaining over:

delegate void CallBackStringA rray(string[] d_string);

[...]

CallBackStringA rray cb = new CallBackStringA rray(populateLi stViews);

Invoke(cb, new object[] { fileList });
Feb 22 '08 #6
I really appreciate everyone taking the time to help. I have a problem
using Jon's example with my string array methods...

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
[...] You don't need to declare the variable
first, and you can just cast to Action<string[]>, giving:

if (InvokeRequired )
{
Invoke ((Action<string >[]) populateListVie ws, fileList);
}
else
{
...
}
First of all

Invoke((Action< string>)writeSt atus, newMsg);

Works fine on my string method, no problem what so ever.

But...

Invoke((Action< string>[])populateListVi ews, fileList);

Doesn't compile, 3 errors:

1) Cannot convert method group 'populateListVi ews' to non-delegate type
'System.Action< string>[]'. Did you intend to invoke the method?

2) The best overloaded method match for
'System.Windows .Forms.Control. Invoke(System.D elegate, params object[])' has
some invalid arguments.

(My method populateListVie ws isn't overloaded, by the way)

3) Argument '1': cannot convert from 'System.Action< string>[]' to
'System.Delegat e'

If I change it to:

Invoke((Action< string[]>)populateListV iews, fileList);

(Which is what I think Jon meant in the first place, as far as I can tell
due to the compile time errors above.)

It compiles fine, but at run time I get a "Parameter count mismatch." logic
error.

My method is: private void populateListVie ws(string[] fileList){...}

And the call is: populateListVie ws(Directory.Ge tFiles(folderPa th));

Directory.GetFi les() returns string[], and my logic was fine when I was
declaring my own delegate or Action<string[]cb = new
Action<string[]>(populateListV iews);
I have tried several different combinations, some compiled and some didn't,
but the ones that compiled always raise that same logic error. What am I
missing?

--
Roger Frost
"Logic Is Syntax Independent"

Feb 22 '08 #7
To be honest, I preferred you earlier example. I believe a delegate
should be named after what it is doing, not given a generic name based
on its parameters and return type. It is convenient to use built-in
delegates, but do they tell readers anything? Look at
Converter<TInpu t, TOutput>, it is one of the most useful delegate
definitions out there - it take something, it returns something. But,
if I'm not converting anything, why am I adding my method name into
it?

I say, using 3.0's delegates is fine because, well, you are forced to
(and they usually make sense). However, especially when doing UI
threading delegates, make as many delegates as you need so that
delegate names make sense. It is no different than finding good names
for any other variable.

I'm not sure why not to use better names and why anyone would suggest
replacing a good name with a more generic one.

IMHO,
Travis
Feb 23 '08 #8
make as many delegates as you need so that
delegate names make sense
Additional to Jon's reply...

If I see a delegate argument JoesCustomWossi t, then if I'm not
familiar I need to look up what the interface is from the metadata/
docs. However, if I see a delegate argument Func<float,floa t,bool>
then I know that it takes 2 floats and returns a bool. Combine that
with the argument name that hopefully indicates its purpose, and I
have everything I need to start coding.

Marc
Feb 23 '08 #9
Peter Duniho wrote:
[...]
You need better co-workers. Seriously.
I had to laugh when I read this -- I've felt the OP's pain on more than one
occasion at both my current place of employ and previous ones.
This is probably the appropriate (well, *accurate*) response to probably two
thirds of the lengthy discussions that take place here that mention work
environment in any way.

Chris.
Feb 25 '08 #10

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

Similar topics

6
2266
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...
0
1362
by: BlueMonkMN | last post by:
I've been trying to think of the right way to design relationships between objects with different desired lifetimes that raise events. If an event source is a relatively permanent object and the event sink is on an object that can come and go, what is the proper way to deal with adding and removing the handler to the event list? Should the...
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...
4
22859
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....
6
2610
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...
0
4758
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...
6
2638
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...
7
3408
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...
69
5521
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...
0
7391
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...
0
7651
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. ...
1
7410
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...
0
5962
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...
1
5320
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...
0
4941
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...
0
3443
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...
1
1869
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1010
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.