6

I read that you can use interfaces and delegates for the same purpose. Like, you can use delegates instead of interfaces.

Can someone provide an example? I've seen an example in the nutshell book but I fail to remember and wanted to ask away.

Is it possible to provide some sample code? Use case?

Thanks.

nawfal
  • 70,104
  • 56
  • 326
  • 368
DarthVader
  • 52,984
  • 76
  • 209
  • 300
  • 3
    possible duplicate of [C# how can a delegate & interface method interchangable](http://stackoverflow.com/questions/2012095/c-how-can-a-delegate-interface-method-interchangable) – H H May 13 '11 at 16:07

3 Answers3

8

If your interface has a single method, then it is more convenient to use a delegate.

Compare the following examples:

Using an interface

public interface IOperation
{
    int GetResult(int a, int b);
}

public class Addition : IOperation
{
    public int GetResult(int a, int b)
    {
         return a + b;
    }
}

public static void Main()
{
    IOperation op = new Addition();
    Console.WriteLine(op.GetResult(1, 2));
}

Using a delegate

// delegate signature.
// it's a bit simpler than the interface
// definition.
public delegate int Operation(int a, int b);

// note that this is only a method.
// it doesn't have to be static, btw.
public static int Addition(int a, int b)
{
    return a + b;
}

public static void Main()
{
    Operation op = Addition;
    Console.WriteLine(op(1, 2));
}

You can see that the delegate version is slightly smaller.

Using anonymous methods and `Func` delegates

If you combine this with built-in .NET generic delegates (Func<T>, Action<T> and similar), and anonymous methods, you can replace this entire code with:

public static void Main()
{
    // Func<int,int,int> is a delegate which accepts two
    // int parameters and returns int as a result
    Func<int, int, int> op = (a, b) => a + b;

    Console.WriteLine(op(1, 2));
}
vgru
  • 49,838
  • 16
  • 120
  • 201
  • Or `Func> op = a => b => a + b; Console.WriteLine(op(1)(2));` – phoog May 13 '11 at 16:47
  • @phoog, @user177883: What phoog demonstrated is known as [currying](http://en.wikipedia.org/wiki/Currying), i.e. transforming a function that takes multiple arguments into a chain of functions each accepting a single argument. It is a very powerful technique used in lambda calculus. Some analogy could be drawn, with an interface method which returns a single method interface as a result. – vgru May 13 '11 at 20:41
2

Delegates can be used in the same way as a single-method interface:

interface ICommand
 {
   void Execute();
 }

delegate void Command();
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
0

When you use delegate:

public delegate T Sum<T>(T a, T b);

class Program
{
    static void Main(string[] args)
    {
        int sum = Test.Sum(new[] {1, 2, 3}, (x, y) => x + y);
    }
}

public static class Test
{
    public static int Sum<T>(IEnumerable<T> sequence, Sum<T> summator)
    {
        // Do work
    }
}

When you use an Interface:

public interface ISummator<T>
{
    T Sum(T a, T b);
}

public class IntSummator : ISummator<int>
{
    public int Sum(int a, int b)
    {
        return a + b;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int sum = Test.Sum(new[] {1, 2, 3}, new IntSummator());
    }
}

public static class Test
{
    public static int Sum<T>(IEnumerable<T> sequence, ISummator<T> summator)
    {
        // Do work
    }
}

Use case - provide a thing that can do only one action. Delegates are good because you don't have to create new classes you can just take a method with the same signature, or even pass a lambda which calls a method with different signature. But Interfaces are more flexible if you decide to get more complex logic:

public interface IArithmeticOperations<T>
{
    T Sum(T a, T b);
    T Sub(T a, T b);
    T Div(T a, T b);
    T Mult(T a, T b);
    //
}

public class IntArithmetic : IArithmeticOperations<int>
{
    public int Sum(int a, int b)
    {
        return a + b;
    }

    public int Sub(int a, int b)
    {
        return a - b;
    }

    public int Div(int a, int b)
    {
        return a / b;
    }

    public int Mult(int a, int b)
    {
        return a * b;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int sum = Test.SumOfSquares(new[] {1, 2, 3}, new IntArithmetic());
    }
}

public static class Test
{
    public static int SumOfSquares<T>(IEnumerable<T> sequence, IArithmeticOperations<T> summator)
    {
        // Do work
    }
}
oxilumin
  • 4,775
  • 2
  • 18
  • 25