The MSDN site compares using delegates instead of an interface, but what makes these two language-level constructs so similar that one could be used over another? They seem to do completely different things?
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
One can view a delegate as equivalent to an interface with a single method. In languages where delegates are not supported, patterns for which one would normally use delegates are often written using interfaces instead.
For example, Java uses anonymous inner classes that implement interfaces where one would normally use an anonymous delegate / lambda expression in C#:
Java:
C#:
In both cases, the intent is to provide a thread with an entry-point. One approach uses an interface, and the other, a delegate, but if you disregard the “plumbing”, it’s clear that interface is serving the same purpose as the delegate. Note that availability to use a lambda-expression to express this idea is not exclusive to delegates. Project Lambda for Java attempts to, amongst other things, bring conversion from a “function of the appropriate type to an anonymous instance of an interface or abstract class which declare just one method.” This may eventually allow for the same terse syntax as the C# version, but without necessarily requiring delegate-types.
Even within the .NET framework, there are equivalences between interface-types and delegate-types, for example
Comparison<T>andIComparer<T>.EDIT: Updated code and made distinction clearer.