Difference Between Delegates and Interfaces

You use delegates when you think of a .NET code that takes callback parameters, which look a lot like strongly typed method pointers in C++. You may not think that you can implement a callback parameter as an interface. Interfaces and delegates have a common key property of allowing you to call a method with the right prototype without knowing which object implements the method, which instance is bound to the call, or the name of the method you're calling.
1. Interface calls are faster than delegate calls. An interface reference is a reference to an instance of an object which implements the interface. An interface call is not that different from an ordinary virtual call to a method. A delegate reference, on the other hand, is a reference to a list of method pointers. While invoking a delegate looks like you're making an indirect call through a method pointer, it's actually a subroutine call that walks the list of method pointers. The overhead involved in making the call and walking the list means that delegate invocation can be two or three times slower than calling a method through an interface reference.
2. Interfaces are also a bit more general than are delegates. A single interface reference gives you access to all the methods of the interface. You can also check if the interface is implemented by this object type, or if the object also implements that other interface. If it does, you can cast the interface reference to an instance reference, or to a reference to another interface. Conversely, you can not go from a delegate to the instances it will call or to any other methods those instances may support.
However, don't conclude from this that you should always implement callbacks via interfaces, not delegates. One key difference between delegates and interfaces is that you can create a delegate to any method with the right prototype.

0 comments:

Post a Comment