Why does the Linq Cast helper not work with the implicit cast operator?

So why my explicit cast work, and the one inside .Cast<> doesn’t?

Your explicit cast knows at compile time what the source and destination types are. The compiler can spot the explicit conversion, and emit code to invoke it.

That isn’t the case with generic types. Note that this isn’t specific to Cast or LINQ in general – you’d see the same thing if you tried a simple Convert method:

public static TTarget Convert<TSource, TTarget>(TSource value)
{
    return (TTarget) value;
}

That will not invoke any user-defined conversions – or even conversions from (say) int to long. It will only perform reference conversions and boxing/unboxing conversions. It’s just part of how generics work.

Leave a Comment