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

Get C# Primer: A Practical Approach 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.