Friday, August 26, 2011

Delegate vs. Interface


In this post I will explain some distinct features of delegate and interface.

All of you might aware about delegate and interface functionality in .Net. The similar kind of functionality can be achieved using both delegate and interface but both have their unique features too. So the question is when to use interface and when to use delegate?

Let’s start understanding using simple example.

Example 1 - Using interface

public interface IMyInterface
{
     void MyMethod(string name);
}
public class MyClass : IMyInterface
{
     public void MyMethod(string name)
     {
         Console.WriteLine("Hello " + name);
     }
}
public static void Main()
{
IMyInterface iCall = new MyClass();
iCall.MyMethod("Mitesh"); //Output: Hello Mitesh
}

Example 2 - Using delegate

public class MyClass
{
    public void MyMethod(string name)
    {
        Console.WriteLine("Hello " + name);
    }
}
public delegate void MyDelegate(string name);
public static void Main()
{
MyClass cls = new MyClass();
       MyDelegate d = cls.MyMethod;
       d("Mitesh"); //Output: Hello Mitesh
}

Output of example 1 and 2 both are same but both example uses different concept example 1 is using Interface and example 2 is using delegate.

Let’s understand when to use Delegate and when to use Interface?

Use Delegate when -

  • You need to use multicast capability.
  • You want to wrap static methods.
  • Delegate can be used from anywhere in the scope they visible.
  • An event pattern is used.
  • You want to use anonymous methods.


Use Interface when -

  • A class needs only one implementation of method.
  • You want to use inheritance feature because interface can inherit from other interface.
  • You want to avoid method pointers overhead. When you call method using delegate it first scan through before executing it but in case of interface it directly calling method. It has some significance performance improvements.
  • Multiple kind of events are supported and need to implements all of them

See also


1 comment:

  1. You have some really good ideas in this article. I am glad I read this. I agree with much of what you state in this article. Your information is thought-provoking, interesting and well-written. Thank you.

    www.imarksweb.org

    ReplyDelete