Delegates Vs Interfaces
Delegates Vs Interfaces
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( ); class sampleClass1 { static void sampleMethod( ) { Console.WriteLine(Executing sampleMethod of sampleClass1); } } class sampleClass2 { static void Main( ) { sampleDelegate dele1 = new sampleDelegate(sampleClass1.sampleMethod); dele1(); } } Example2: Using Interface interface ITestInterface { void sampleMethod( ); } class sampleClass1 : ITestInterface { void sampleMethod( ) { Console.WriteLine(Executing sampleMethod of sampleClass1);
} } class sampleClass2 { static void Main( ) { sampleClass1 obj1 = new sampleClass1( ); obj1.sampleMethod( ); } } 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 { You are actually overriding the interface method. After implementing the method, you are accessing it in Main( ) method of sampleClass2. Both the examples intend in separating declaration from implementation of sampleMethod. And both these examples end up in the same output: Executing sampleMethod of sampleClass1 But the examples are using two different concepts called delegate and interface. Now it is clear that both delegates and interfaces can be used to attain the same functionality.