Cast usage
The benefit of Cast
comes when your collection only implements IEnumerable
(ie. not the generic version). In this case, Cast
converts all elements to TResult
by casting, and returns IEnumerable<TResult>
. This is handy, because all the other LINQ extension methods (including Select
) is only declared for IEnumerable<T>
. In code, it looks like this:
IEnumerable source = // getting IEnumerable from somewhere
// Compile error, because Select is not defined for IEnumerable.
var results = source.Select(x => ((string)x).ToLower());
// This works, because Cast returns IEnumerable<string>
var results = source.Cast<string>().Select(x => x.ToLower());
Cast
and OfType
are the only two LINQ extension methods that are defined for IEnumerable
. OfType
works like Cast
, but skips elements that are not of type TResult
instead of throwing an exception.
Cast and implicit conversions
The reason why your implicit conversion operator is not working when you use Cast
is simple: Cast
casts object
to TResult
- and your conversion is not defined for object
, only for your specific type. The implementation for Cast
is something like this:
foreach (object obj in source)
yield return (TResult) obj;
This "failure" of cast to do the conversion corresponds to the basic conversion rules - as seen by this example:
YourType x = new YourType(); // assume YourType defines an implicit conversion to string
object o = x;
string bar = (string)x; // Works, the implicit operator is hit.
string foo = (string)o; // Fails, no implicit conversion between object and string
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…