O'Reilly logo

Pro C# 2010 and the .NET 4 Platform, Fifth Edition by Andrew Troelsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required