December 2001
Intermediate to advanced
416 pages
8h 16m
English
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 ...
Read now
Unlock full access