473,385 Members | 1,829 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,385 software developers and data experts.

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 callBackStringArray(string[] d_string);

delegate void callBackInt(int d_int);

delegate void callBackSB(string 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 2495
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,boolmatches 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.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
Roger Frost <fr*****@hotmail.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,bool>
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*****@hotmail.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<Tdelegate. 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 populateListViews(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[]>(populateListViews);

//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 CallBackStringArray(string[] d_string);

[...]

CallBackString cb = new CallBackString(populateListViews);

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

"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
On Thu, 21 Feb 2008 23:22:22 -0800, Roger Frost <fr*****@hotmail.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<Tdelegate. 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 CallBackStringArray(string[] d_string);

[...]

CallBackStringArray cb = new CallBackStringArray(populateListViews);

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.comwrote in message
news:MP*********************@msnews.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>[]) populateListViews, fileList);
}
else
{
...
}
First of all

Invoke((Action<string>)writeStatus, newMsg);

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

But...

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

Doesn't compile, 3 errors:

1) Cannot convert method group 'populateListViews' 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.Delega te, params object[])' has
some invalid arguments.

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

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

If I change it to:

Invoke((Action<string[]>)populateListViews, 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 populateListViews(string[] fileList){...}

And the call is: populateListViews(Directory.GetFiles(folderPath));

Directory.GetFiles() returns string[], and my logic was fine when I was
declaring my own delegate or Action<string[]cb = new
Action<string[]>(populateListViews);
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<TInput, 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 JoesCustomWossit, 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,float,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
On Mon, 25 Feb 2008 05:27:03 -0800, Chris Shepherd <ch**@nospam.chsh.ca>
wrote:
If my understanding is correct, there's no funny business. The second
parameter is a *params* object[]
Ah, right. It's funny...I was actually looking for that "params" keyword
in the docs, and didn't see it. When I went back and looked at the exact
same page I'd looked at before, sure enough there it was.

I think someone is messing with my head. :)

Pete
Feb 25 '08 #11

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

Similar topics

6
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...
0
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...
3
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...
4
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...
6
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...
0
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...
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
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,...

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.