The short answer would be simply: the Cast<T>
method doesn't support custom conversion operators.
In the first example:
B b = a;
B b2 = (B)a;
the compiler can see this B(A a)
operator during static analysis; the compiler interprets this as a static call
to your custom operator method. In the second example:
foreach (object obj in source)
yield return (T)obj;
that has no knowledge of the operator; this is implemented via unbox.any
(which is the same as castclass
if T
is a ref-type).
There is also a third option: if you went via dynamic
, the runtime implementation tries to mimic compiler rules, so this will find the operator ... but not as part of the C#-to-IL compile step:
dynamic b = a; // note that `dynamic` here is *almost* the same as `object`
B b2 = b;