I have an explicit conversion defined from type Bar
to type Foo
.
public class Bar
{
public static explicit operator Foo(Bar bar)
As all other answers pointed type is not known in compile time since Cast
method is not generic
. It holds type of object
and makes a explicit cast to T
. this fails because you don't have conversion operator from object
to Foo
. And that is not possible also.
Here is a work around using dynamics in which cast will be done in runtime.
public static class DynamicEnumerable
{
public static IEnumerable DynamicCast(this IEnumerable source)
{
foreach (dynamic current in source)
{
yield return (T)(current);
}
}
}
Then use it like
var result = bars.DynamicCast();//this works