O'Reilly logo

C# Primer: A Practical Approach by Stanley B. Lippman

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

4.4. Explicit Interface Member Implementations

Given an entity of type object, how can we discover if it supports a particular interface? One way is simply to ask, using the is operator:

public static void iterate( object o )
{
      // true if o implements IEnumerable
      if ( o is IEnumerable )
      {
           IEnumerable ie = (IEnumerable) o;
           IEnumerator iter = ie.GetEnumerator();

           while ( iter.MoveNext() )
                   Console.WriteLine( "{0} ",
                           iter.Current.ToString() );
      }
}

iterate() is an example of a generic function in C#. We have no idea as to the actual type that o refers to. We ask if it supports the IEnumerable interface. If it does not, that's an end to it. If it does, we access it through an abstract IEnumerator object, moving through the elements in turn. We have ...

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