Home All Groups Group Topic Archive Search About

Is there any predefined delegate with no argument?

Author
9 Nov 2007 7:08 AM
Dancefire
Hi,

I am looking for a predefined delegate which in form:

delegate void NoArgument();

It's quite useful than other delegate with argument, I found
MethodInvoker in WinForms, which defined in such form, but I don't
want to add WinForm reference all the time, since my code nothing
relative the WinForm.

The reason why I use no argument delegate is quite often is that it's
quite easy to access local variable if I use anonymous methods, which
may decrease the prerequest of declare a delegate with some argument
to pass in.

For example, when I try to access WinForm in thread safe way, I
defined a static function DoThreadSafe():

        private static void DoThreadSafe(Control control,
MethodInvoker function)
        {
            if (function != null)
            {
                if (control.InvokeRequired)
                {
                    control.Invoke(function);
                }
                else
                {
                    function();
                }
            }
        }

When I use it, I do not need any parameter to pass to the "function",
such as:

           value = 123;
           DoThreadSafe(progressBar1, delegate
            {
                progressBar1.Value = value;
            });

It is really easy to access the variable which is accessible in
current scope. I found many such cases which treat the delegate just a
block of code to execute without any need of argument.

I think that it's better to treat void delegate with no argument as a
special, and predefined in dotnet framework, and may be more
convinient to declare and call in the future version of C#. Is there
any existing delegate in .net framework?

Regards,

Author
9 Nov 2007 7:56 AM
Jon Skeet [C# MVP]
Dancefire <Dancef***@gmail.com> wrote:
> I am looking for a predefined delegate which in form:
>
> delegate void NoArgument();
>
> It's quite useful than other delegate with argument, I found
> MethodInvoker in WinForms, which defined in such form, but I don't
> want to add WinForm reference all the time, since my code nothing
> relative the WinForm.

One alternative prior to .NET 3.5 is ThreadStart. However, using that
has an implication to the reader which isn't valid unless you really
are starting a thread.

In .NET 3.5 there's the Action delegate, which has overloads by type
parameters:

void Action()
void Action<T>(T arg0)
void Action<T1,T2>(T1 arg0, T2 arg1)
etc

(In .NET 2.0 just the single-argument version is present.)

--
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

AddThis Social Bookmark Button