9.6. Interfaces As Return Values

Interfaces can also be used as method return values. For example, you could write a method that takes an array of Shape objects and returns a reference to the first item that supports IPointy:

// This method returns the first object in the
// array that implements IPointy.
static IPointy FindFirstPointyShape(Shape[] shapes)
{
  foreach (Shape s in shapes)
  {
    if (s is IPointy)
      return s as IPointy;
  }
  return null;
}

You could interact with this method as follows:

static void Main(string[] args)
{
  Console.WriteLine("***** Fun with Interfaces *****\n");
// Make an array of Shapes.
  Shape[] myShapes = { new Hexagon(), new Circle(),
                       new Triangle("Joe"), new Circle("JoJo")};

  // Get first pointy item. // To be safe, you'd ...

Get Pro C# 2010 and the .NET 4 Platform, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.