Information Technology Reference
In-Depth Information
MyType t = null ;
if (o is MyType )
t = o as MyType ;
That's inefficient and redundant. If you're about to convert a type using
as , the is check is simply not necessary. Check the return from as against
null; it's simpler.
Now that you know the difference among is , as , and casts, which opera-
tor do you suppose the foreach loop uses? Foreach loops can operate on
nongeneric IEnumerable sequences and have the type coercion built into
the iteration. (You should prefer the type-safe generic versions whenever
possible. The nongeneric version exists for historical purposes, and to sup-
port some late binding scenarios.)
public void UseCollection( IEnumerable theCollection)
{
foreach ( MyType t in theCollection)
t.DoStuff( );
}
foreach uses a cast operation to perform conversions from an object to
the type used in the loop. The code generated by the foreach statement
roughly equates to this hand-coded version:
public void UseCollectionV2( IEnumerable theCollection)
{
IEnumerator it = theCollection.GetEnumerator();
while (it.MoveNext())
{
MyType t = ( MyType )it.Current;
t.DoStuff();
}
}
foreach needs to use casts to support both value types and reference
types. By choosing the cast operator, the foreach statement exhibits the
same behavior, no matter what the destination type is. However, because
a cast is used, foreach loops can cause an InvalidCastException to be
thrown.
Because IEnumerator.Current returns a System.Object, which has no con-
version operators, none is eligible for this test. A collection of SecondType
objects cannot be used in the previous UseCollection() function because
 
Search WWH ::




Custom Search