Delegates Vs Interfaces in C# (C Sharp)Delegates and Interfaces are two distinct concepts in C# but they share a commonality. Both delegates and interfaces only include the declaration. Implementation is done by a different programming object. To make it clear, consider the following two examples:
Example1: Using Delegate delegate
void sampleDelegate( ); Example2: Using Interface interface
ITestInterface{ In Example1, sampleDelegate only has the declaration. No implementation is provided for the delegate. However, this delegate is used to wrap any methods matching its signature. In this example, delegate is used to wrap and execute sampleClass1.sampleMethod. In Example2, interface ITestInterface has a method called sampleMethod which has only the declaration and not the definition or implementation code. This is very similar to the delegate. Implementation of sampleMethod is done in the class sampleClass1, for which the class has to implement the interface using the following line of code: class sampleClass1
: ITestInterface { Both the
examples intend in separating declaration from implementation of sampleMethod.
And both these examples end up in the same output: What
is the difference between delegate and interface? Rest of this article will focus on answering these questions with the help of the comparison chart provided below:
|