Advanced C# - Delegates Versus Interfaces
(Page 4 of 4 )
A problem that can be solved with a delegate can also be solved with an interface. For instance, the following explains how to solve our filter problem using an ITransformer interface:
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 Test : ITransformer
{
static void Main()
{
int[] values = new int[] {1, 2, 3};
Util.TransformAll(values, new Test());
foreach (int i in values)
Console.WriteLine (i);
}
public int Transform (int x) { return x * x; }
}
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 listener needs to implement the interface multiple times.
In theITransformerexample, we don’t need to multicast. However, the interface defines only a single method. Furthermore, our listener may need to implementITransformermultiple times, to support different transforms, such as square or cube. With interfaces, we’re forced into writing a separate type per transform, sinceTestcan only implementITransformeronce. This is quite cumbersome:
class Test
{
static void Main()
{
int[] values = new int[] {1, 2, 3};
Util.TransformAll(values, new Cuber());
foreach (int i in values)
Console.WriteLine (i);
}
class Squarer : ITransformer
{
public int Transform (int x) { return x * x; }
}
class Cuber : ITransformer
{
public int Transform (int x) {return x * x * x; }
}
}
Please check back next week for the continuation of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|