Using Multiple Interfaces

Environment: .NET / C#

One of the benefits of implementing interfaces instead of inheriting from a class is that you can implement more than one interface at a time. This gives you the power to do multiple inheritance without some of the downside.

To implement multiple interfaces in C#, you separate each included interface with a comma. For example, to include both an Ishape and an IshapeDisplay interface in a Square class, you use the following:

class Square : IShape, IShapeDisplay
{
   ...
}

You then need to implement all the constructs within both interfaces. Listing 1 illustrates the use of multiple interfaces.

Listing 1 – Multi.cs – Implementing Multiple Interfaces in a Single Class

 1:  //  Multi.cs -
 2:  //-----------------------------------------------------------
 3:
 4:  using System;
 5:
 6:  public interface IShape
 7: {
 8:     // Cut out other methods to simplify example.
 9:     double Area();
10:     int Sides { get; }
11:  }
12:
13:  public interface IShapeDisplay
14:  {
15:     void Display();
16:  }
17:
18:  public class Square : IShape, IShapeDisplay
19:  {
20:     private int InSides;
21:     public  int SideLength;
22:
23:     public int Sides
24:     {
25:        get { return InSides; }
26:     }
27:
28:     public double Area()
29:     {
30:        return ((double) (SideLength * SideLength));
31:     }
32:
33:     public double Circumference()
34:     {
35:        return ((double) (Sides * SideLength));
36:     }
37:
38:     public Square()
39:     {
40:        InSides = 4;
41:     }
42:
43:     public void Display()
44:     {
45:        Console.WriteLine("nDisplaying Square information:");
46:        Console.WriteLine("Side length: {0}", this.SideLength);
47:        Console.WriteLine("Sides: {0}", this.Sides);
48:        Console.WriteLine("Area: {0}", this.Area());
49:     }
50:  }
51:
52:  public class Multi
53:  {
54:     public static void Main()
55:     {
56:        Square mySquare = new Square();
57:        mySquare.SideLength = 7;
58:
59:        mySquare.Display();
60:     }
61:  }

Output

Displaying Square information:
Side length: 7
Sides: 4
Area: 49

You can see that two interfaces are declared and used in this listing. In Line 18, you can see that the Square class will implement the two interfaces. Because both are included, all members of both interfaces must be implemented by the Square class. In looking at the code in Lines 23 – 49, you see that all the members are implemented. You can implement multiple interfaces in your own applications in the same way.

Downloads


Download source – MInherit.zip – 1 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read