Implicit conversion from IEnumerable<int> to Foo<IEnumerable<int>> fails, but works for int[] to Foo<IEnumerable<int>>

Viewed 65

Sorry for the clumsy title, but SO wouldn't let me leave it at "implicit conversion not working as expected".

Consider this trivial generic type:

public class Foo<T> {
    public T Bar;
    public Foo(T bar) => Bar = bar;
    public static implicit operator Foo<T>(T bar) => new(bar);
}

Notice the implicit conversion that (at least in my mind) should allow me to create a Foo<T> directly from any T like so:

int[] xs = new[] { 1, 2, 3 };
IEnumerable<int> ys = xs.AsEnumerable();
Foo<IEnumerable<int>> foo = ys; // CS0266

However the above will produce a compiler error:

CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'Foo<System.Collections.Generic.IEnumerable<int>>'. An explicit conversion exists (are you missing a cast?)

Funnily enough, the below code is working without problems:

int[] xs = new[] { 1, 2, 3 };
Foo<IEnumerable<int>> foo = xs; // no error

And using an explicit cast "fixes" the compiler error, but crashes at runtime:

int[] xs = new[] { 1, 2, 3 };
IEnumerable<int> ys = xs.AsEnumerable();
Foo<IEnumerable<int>> foo = (Foo<IEnumerable<int>>)ys; // InvalidCastException

InvalidCastException: Unable to cast object of type 'System.Int32[]' to type 'Foo`1[System.Collections.Generic.IEnumerable`1[System.Int32]]'.

What is going on here? I'm totally stumped and don't have the slightest clue.

.NET Fiddle: https://dotnetfiddle.net/wNHUtl

0 Answers
Related