Information Technology Reference
In-Depth Information
the conversion fails, as you already saw. The foreach statement (which
uses a cast) does not examine the casts that are available in the runtime type
of the objects in the collection. It examines only the conversions available
in the System.Object class (the type returned by IEnumerator.Current)
and the declared type of the loop variable (in this case, MyType).
Finally, sometimes you want to know the exact type of an object, not just
whether the current type can be converted to a target type. The is opera-
tor returns true for any type derived from the target type. The GetType()
method gets the runtime type of an object. It is a more strict test than the
is or as statement provides. GetType() returns the type of the object and
can be compared to a specific type.
Consider this function again:
public void UseCollectionV3( IEnumerable theCollection)
{
foreach ( MyType t in theCollection)
t.DoStuff();
}
If you made a NewType class derived from MyType, a collection of NewType
objects would work just fine in the UseCollection function:
public class NewType : MyType
{
// contents elided.
}
If you mean to write a function that works with all objects that are
instances of MyType, that's fine. If you mean to write a function that works
only with MyType objects exactly, you should use the exact type for com-
parison. Here, you would do that inside the foreach loop. The most com-
mon time when the exact runtime type is important is when doing
equality tests (see Item 6). In most other comparisons, the .isinst com-
parisons provided by as and is are semantically correct.
The .NET Base Class Library (BCL) contains a method for converting ele-
ments in a sequence using the same type of operations: Enumerable
.Cast<T>() converts each element in a sequence that supports the classic
IEnumerable interface:
IEnumerable collection = new List < int >()
{ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
 
Search WWH ::




Custom Search