In your particular example, maybe it's not important. (It's not clear what it's trying to achieve.)
But suppose you wanted to make the method execute the same MyFunc1
or MyFunc2
for several different inputs. For example, suppose you were implementing the Newton-Raphson method, to operate over a general function. In that situation, you couldn't call the function once and pass that into the method - you want to pass the actual function into the method, so that the method can call it with whatever inputs it needs.
A similar example is sorting. For example, using LINQ you can write something like:
var sorted = people.OrderBy(x => x.Age).ToList();
There we're passing a function to project each source element to the ordering key. We don't have to execute that function ourselves - OrderBy
will do it for us (lazily).
Of course, all of this can be done with single-method interfaces too - delegates and single-method interfaces have a lot in common. However, delegates have the following benefits over single-method interfaces:
- Delegates are multi-cast - they can be combined/removed, usually for the sake of events
- You can execute them asynchronously with BeginInvoke/EndInvoke
- You can build them with anonymous methods and lambda expressions
- You can represent logic as data via expression trees using lambda expresions; these can then be compiled into delegates
- You can build a delegate from any method with the appropriate signature - so for example a single class can have multiple methods "implementing" the same delegate type, whereas you can't implement an interface multiple times in one class
- Likewise delegate implementation methods can be private, whereas interface methods have to be public (or somewhat-public via explicit interface implementation)
All of these could have been addressed differently using single-method interfaces, of course, but delegates are a handy alternative.
In conclusion: delegates are very useful. Just because you've written some trivial code which doesn't particularly require them doesn't mean they're not useful. I would strongly suggest you look into LINQ, event handlers and the TPL, all of which use delegates heavily.