I can't be the only one getting tired of defining and naming a delegate for just a single call to something that requires a delegate. For example, I wanted to call .Refresh() in a form from possibly other threads, so I wrote this code:
private void RefreshForm()
{
if (InvokeRequired)
Invoke(new InvokeDelegate(Refresh));
else
Refresh();
}
I'm not even sure I have to, I just read enough to be scared that it won't work at some later stage.
InvokeDelegate is actually declared in another file, but do I really need an entire delegate dedicated just for this? aren't there any generic delegates at all?
I mean, for example, there's a Pen class, but there's also Pens.pen-of-choice so you don't have to remake the whole thing. It's not the same, but I hope you understand what I mean.
There's the Action delegate you could use, like so:
Or, with lambda syntax:
Finally there's anonymous delegate syntax:
In this specific case you can (and should) just use MethodInvoker to do this... that is why it exists.
If you were doing something else you could, as others have answered use Func<T,...> or Action<T,...> if they fit your use case.
Short version:
Then you can also drop the check of InvokeRequired; you can just call it as it is. Works also if you need to pass parameters, so there is no need for other parameter-specific delegates (works just as well with the parameter-less Action delegate as well):
Yes. In .NET 3.5 you can use Func and Action delegates. The Func delegates return a value, while Action delegates return void. Here is what the type names would look like:
I don't know why they stopped at 4 args each, but it has always been enough for me.
Defining your own delegates can really make debugging easier, if only because Intellisense can tell you the names of your parameters. For example, you write a delegate like this:
When you use it code, .NET will inform you of the parameter names, delegate name, etc, so there's a lot of context right in the delegate definition if you aren't sure exactly how something is used.
However, if you don't mind sacrificing Intellisense, there is already a class of delegates definined in the System namespace which can be used as ad-hoc delegates:
Only
Action
andAction
exist in .NET 2.0, but its easy enough to declare a helper class with the remaining delegates you need for these kind of miscellaneous ad hoc functions.Yes, there are generic delegates.
Action<T1, T2...>
is a generic delegate that takes some parameters and returns no value, andFunc<T1, T2...R>
is a generic delegate that takes some parameters and returns a value.