Delegates Versus Interfaces - CSharp Custom Type

CSharp examples for Custom Type:delegate

Introduction

A problem that can be solved with a delegate can also be solved with an interface.

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.

For instance, we can rewrite our original example with an interface called ITransformer instead of a delegate:

Demo Code

using System;//from www . java  2  s. co  m
public interface ITransformer
{
    int Transform(int x);
}
public class Util
{
    public static void TransformAll(int[] values, ITransformer t)
    {
        for (int i = 0; i < values.Length; i++)
            values[i] = t.Transform(values[i]);
    }
}
class Squarer : ITransformer
{
    public int Transform(int x) => x * x;
}
class MainClass {
    static void Main()
    {
        int[] values = { 1, 2, 3 };
        Util.TransformAll(values, new Squarer());
        foreach (int i in values)
            Console.WriteLine(i);
    }
}

Result


Related Tutorials