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?
Cast usage
The benefit of
Castcomes when your collection only implementsIEnumerable(ie. not the generic version). In this case,Castconverts all elements toTResultby casting, and returnsIEnumerable<TResult>. This is handy, because all the other LINQ extension methods (includingSelect) is only declared forIEnumerable<T>. In code, it looks like this:CastandOfTypeare the only two LINQ extension methods that are defined forIEnumerable.OfTypeworks likeCast, but skips elements that are not of typeTResultinstead of throwing an exception.Cast and implicit conversions
The reason why your implicit conversion operator is not working when you use
Castis simple:CastcastsobjecttoTResult– and your conversion is not defined forobject, only for your specific type. The implementation forCastis something like this:This “failure” of cast to do the conversion corresponds to the basic conversion rules – as seen by this example: