tags:

views:

125

answers:

5
+2  A: 

There is no advantage in the code you posted. In your code, using the delegate just adds complexity as well as an extra runtime cost - so you're better off just calling the method directly.

However, delegates have many uses. "Passing around" to other methods is the primary usage, though storing a function and using it later is also very useful.

LINQ is built on top of this concept entirely. When you do:

var results = myCollection.Where(item => item == "Foo");

You're passing a delegate (defined as a lambda: item => item == "Foo") to the Where function in the LINQ libraries. This is what makes it work properly.

Reed Copsey
A: 

It's only useful if you have to pass the delegate around. If you can resolve the function at compile time, it's less useful.

John Weldon
You can delegate any existing function in one line, I don't really think there is an advantage unless you're doing it like 10,000+ times (less objects created).
Aren
A: 

you can use delegates as "function pointers", so you can give the functions or "actions" to other functions to execute.

what also would be interesting with delegates is the possibility of "precompiling", like you "build" a new function and then return this function to your application

A: 

With the static method you have to pass in all the variables needed.
With the delegate you could inline your implementation and have access to the variables in scope.

Justin
A: 

A very useful function of delegates is that you can send them wherever you want. It's like having your function everywhere you need it. A big use for this is event handling. Say you have a button, and when a user clicks this button you want any number of functions to be called. If you think about this there are a couple of ways you could do this:

You Could: Call a function that calls each other function you want called. This means that for each new function you want to be called, you must hard code it into this function. Very annoying.

OR You could have a public list of the names of each function you want to call (delegates), and anyone can add or remove these functions at any time without the owner of the click event having to know or even do any work regarding any of them. When the click event happens, every event in the list is called and sent the same parameters, and you're done.

BinaryTox1n