I have a type with implicit conversion operators to most base types and tried to use .Cast<string>()
on a collection of this type, which failed. As I dug into it, I noticed that casting via as
doesn't use implicit or explicit conversion and just won't compile, so I guess that's where .Cast
falls down. So this fails
var enumerable = source.Cast<string>();
but this works
var enumerable = source.Select(x => (string)x);
So what's the benefit of Cast? Sure, it's a couple of characters shorter, but seems a lot more limited. If it can be used for conversion, is there some benefit other than the more compact syntax?
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.
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
I checked the MSDN page for Cast<TResult>
, and it is an extension method to types that implement (the non-generic) IEnumerable
interface.
It can convert a collection class (such as ArrayList
) which doesn't implement IEnumerable<T>
to one that does, allowing the richer operations (such as Select<T>
) to be performed against it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With