Differentiate between delegates and interfaces

Delegates:

  • Delegates are reference-types, so they allocate an entire object only to reference a method.
  • Delegates are the fastest to call when you know all parameter types at compile-time.
  • Delegates allow the use of anonymous delegates which really simplify creating single-line or very small delegates.
  • Delegates can reference a private method without the requirement to create a new type.

Interfaces:

  • Interfaces don’t allocate new objects, so they are faster to get.
  • Interfaces are faster for single-use cases, as only one object will be created instead of two.
  • If well designed, interfaces allow for generic (untyped) uses that are faster than DynamicInvoke of delegates.
  • If well designed, generic interfaces can be accessed by an untyped interface that has the same signature methods and parameters, only changing the generic type parameters by object.
  • Interfaces allow different calling possibilities (like the Convert and TryConvert).
  • Interfaces are a little slower to call with the rightly typed parameters.
  • Interfaces don’t have anonymous compile-time support.
  • Interfaces require full types to be created even if a single method is needed.

A delegate design may be a better choice than an interface design if one or more of these conditions are true: 

  • The interface defines only a single method.
  • Multicast capability is needed.
  • The subscriber needs to implement the interface multiple times.

No comments:

Post a Comment