Combining Interfaces
Another powerful feature of C# is the ability to combine two or more interfaces together such that a class need only implement the combined result. For example, let's say you want to create a new TreeView class that implements both the IDragDrop and ISortable interfaces. Since it's reasonable to assume that other controls, such as a ListView and ListBox, would also want to combine these features, you might want to combine the IDragDrop and ISortable interfaces into a single interface: -
using System;
public class Control
{
}
public interface IDragDrop
{
void Drag();
void Drop();
}
public interface ISerializable
{
void Serialize();
}
public interface ICombo : IDragDrop, ISerializable
{
// This interface doesn't add anything new in
// terms of behavior as its only purpose is
// to combine the IDragDrop and ISerializable
// interfaces into one interface.
}
public class MyTreeView : Control, ICombo
{
public void Drag()
{
Console.WriteLine("MyTreeView.Drag called");
}
public void Drop()
{
Console.WriteLine("MyTreeView.Drop called");
}
public void Serialize()
{
Console.WriteLine("MyTreeView.Serialize called");
}
}
class CombiningApp
{
public static void Main()
{
MyTreeView tree = new MyTreeView();
tree.Drag();
tree.Drop();
tree.Serialize();
}
With the ability to combine interfaces, you can not only simplify the ability to aggregate semantically related interfaces into a single interface, but also add additional methods to the new "composite" interface, if needed.