C Sharp

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.

Summary

Interfaces in C# allow the development of classes that can share features but that are not part of the same class hierarchy. Interfaces play a special role in C# development because C# doesn't support multiple inheritance. To share semantically related methods and properties, classes can implement multiple interfaces. Also, the is and as operators can be used to determine whether a particular interface is implemented by an object, which can help prevent errors associated with using interface members. Finally, explicit member naming and name hiding can be used to control interface implementation and to help prevent errors.

by BrainBellupdated
Advertisement: