Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to Use Delegates Instead of Interfaces

According to this article, it says:

Use a delegate in the following circumstances:

  • A class may need more than one implementation of the method.

Use an interface in the following circumstances:

  • A class only needs one implementation of the method.

Can someone explain this to me?

like image 384
Richard Avatar asked Jun 26 '12 09:06

Richard


1 Answers

That is... odd and confusing. If you only needed one implementation of a method... use a method (perhaps a virtual method). As with interfaces, part of the point of delegates is that you can substitute multiple different implementations.

If I had to summarise:

a delegate-type is very-much like an interface that only exposes a single method, and a delegate-instance is very-much like an instance of a class that implements that interface - just with lots of compiler sexiness to make it really easy to write, i.e. x => 2 * x, and without (sometimes) needing the instance.

a delegate also has some other useful tricks geared towards events (multi-cast, etc), but that sounds unrelated to the context of the article.

like image 72
Marc Gravell Avatar answered Oct 05 '22 04:10

Marc Gravell