Differences between delegates and interfaces in C#

Goud.Kv
Posted by in C# category on for Intermediate level | Points: 250 | Views : 20205 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.

Introduction

So far, we have studied about delegates in C#. Now let's see the differences between delegates and interfaces with examples in this chapter.

Objective

The main objective of this article is to learn the differences, advantages and disadvantages of delegates over interfaces in C# programming.

Delegates Vs Interfaces

We already know that delegates and interfaces performs almost similar functionalities in C# programming. In other words, any problem that can be solved with delegate can also be solved with interface.

In real time delegates are faster to execute where as interfaces are faster to get.

Let's have an example program for delegates,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    public delegate int Changer(int a);  // declaring delegate variable

    class MyClass                       // class
    {
        public static void Change(int[] val, Changer ch) // This is our utility method
        {                                                // Observe the delegate parameter 'ch' in this method
            for (int i = 0; i < val.Length; i++)
                val[i] = ch(val[i]);
        }
    }

    class Program
    {
        static int Square(int side)         // static method
        {
            return side * side;                // logic for finding area
        }

        static void Main()
        {
            int[] vals = { 2, 3, 4, 5 };  // integer array
            MyClass.Change(vals, Square); // Calling the utility method

            foreach (int itm in vals)    // logic to print the area's of items.
            {
                Console.WriteLine(itm);  // prints the values
            }
        }
    }
}
In the above program, we used delegate to execute an integer array. Changer() is our delegate with an integer parameter a.

Now, observe the method Change() with our delegate (Changer()) as one of the parameter to specify a plug-in transform.

And in the main method, calling the Change() method with an integer array vals and a static method Square() (a plug-in method).

This code will print the areas of the Square as following,


Now the same thing can be achieved by using interfaces. Following code shows how to do the same with interfaces instead of delegates,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{

    class Program
    {
        public interface IChanger        // Interface
        {
            int Change(int a);
        }

        public class MyClass             // Utility class
        {
            public static void ChangeThem(int[] val, IChanger C)
            {
                for (int i = 0; i < val.Length; i++)
                    val[i] = C.Change(val[i]);
            }
        }

        class Square : IChanger         // class Square implementing IChanger interface 
        {
            public int Change(int s)    // writing interface member
            {
                return s * s;
            }
        }

        static void Main()
        {
            int[] nums = { 2, 3, 4, 5 };
            MyClass.ChangeThem(nums, new Square());
            foreach (int number in nums)
            {
                Console.WriteLine(number);
            }
        }
    }
}
In the above code, we have an interface IChanger. And we have a public class MyClass with plug-in transform method ChangeThem().

Observe that we have used interface IChanger as the second parameter of the method ChangeThem() to specify the plug-in transform.

In the Main() method, we have declared an integer array nums. And then calling the ChangeThem() with locally declared array (nums) and instance of another class (Here we have the class Square which extends IChanger interface) will invoke the same in the MyClass.

Press Ctrl + F5 to see the following lines in your console,


Differences between Delegates and Interfaces

DelegateInterface
We can define multiple methods by using delegate.Interface defines only a single method.
No need to implement multiple times.Need to implement the interface multiple times.
Fastest to call at runtime when we know all the parameter types.Well designed interfaces are allowed for generic uses which are very faster than delegate's DynamicInvoke.
Recommended for multi use cases as it is more flexible than interface.Very useful and faster for single use cases.
Allows the use of anonymous delegatesAnonymous compile-time support is not possible in interfaces.
Multicast is supported.Interface doesn't support multicast.
Faster to execute.Slower than delegates to execute.
Slower to get.Faster to get as they don't allocate the new objects.

Conclusion

In this article, we have seen the differences,  advantages and disadvantages of delegates over interfaces with examples. Hope you understand.

Thanks for reading,

Regards,
Krishna.

Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Posted by: Vivek.Ramapuram on: 11/10/2014 | Points: 25
Nice article
Thanks
Posted by: Kishutvn on: 8/11/2016 | Points: 25
Nice article. But , i think ...Interface defines only a single method. ..may not be true.

Login to post response

Comment using Facebook(Author doesn't get notification)