Conversion operators are a faff to use with generics - generics don't support any static operator overloads. Because of this, the (T)
cast is performing a non-converting type check (generics need to use the same IL for every possible T
, remember) - a basic castclass
.
The only "simple" way of doing what you want is to cheat with dynamic
:
return externalItems.Select(item => (T)(dynamic)item);
Since the C#-specific dynamic
provider knows all the common rules of C#, it knows about conversion operators, and will apply them on-demand. There is a slight performance cost associated with this, but it isn't as bad as it looks at first glance, as the strategy is cached (as IL) once per type - it doesn't perform per-item reflection.