Should we go with Delegate or Interface?

Delegate and Interface can provide you a a great mechanism that will separate the definition from the declaration.
Before we go into the detail about when to use what, let us first understand what is delegate (C/C++ pointers) and what is interface.

What is Delegate?

A delegate is a pointer variable declared as a variable of custom build type that can stores the reference to a function. The type should define method’s return type and its parameter types.

The following define a delegate type called StreamWriter

delegate bool StreamWriter (string text);

Here’s a complete example:

delegate void StreamWriter (string text);

class Test {
static void Main() {
StreamWriter t = ConsoleWriter;
t("Print this");
}

public void ConsoleWriter(string value) {
Console.WriteLine(value);
}
}

What is Interface?

An interface defines a template for its implementors. Just like an construction architect gives a blue print look through model, a software architect can use Interface as a tool for a blue print look for classes.

Should we go for Delegate or Interface?

  • Use a delegate in the following circumstances:
  • An eventing design pattern is used; that is multicast capability is needed.
  • It is desirable to encapsulate a static method.
  • The caller has no need to access other properties, methods, or interfaces on the object implementing the method i.e. The interface defines only a single method.
  • Easy composition is desired.
  • A class may need more than one implementation of the method; The subscriber needs to implement the interface multiple times.

Use an interface in the following circumstances:

  • There is a group of related methods that may be called.
  • A class only needs one implementation of the method.
  • The class using the interface will want to cast that interface to other interface or class types.
  • The method being implemented is linked to the type or identity of the class: for example, comparison methods.

In conclusion, it all comes down to your architecture. If your architecture needs event looks like callback operations. Then delegate wins over Interface. But if you want to define few methods along with some properties to be available through template then interface is your best choice.