Monday, June 24, 2019

Difference between Interface and Delegate in c#


Interface is a contract, a method declared inside of interface, class which implementing that Interface should provide definition for declared method inside interface.

In case of delegate, if a class (let's say A) method needs callback function as a parameter or exposing a delegate (same like event) to subscribe. you need to implement callback method with same signature as delegate to subscribe delegate/callback.

In both cases (in case of interface and in case of delegate) you need to define a method with declared signature by interface/delegate so, in case of single method interface seems there is no difference between interface and delegate.

let's dig in detail,

  • for an interface method implementation, it's necessary to declare it public.
  • if interface has more than one method, implementer of interface need to define all the methods of interface.
  • we can subscribe a private method, or anonymous method to delegate, which is not possible in case of interface.
  • In case of interface, we need to define method same as method declared in interface (same name) but in case of delegate we can assign any method whose signature is same as delegate signature.
  • delegate provide multicast functionality, we can subscribe multiple methods to delegate but not to interface.
* Please let me know your comments...

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...