3

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

Good Night Nerd Pride
  • 8,245
  • 4
  • 49
  • 65
  • This has been explained [here](https://stackoverflow.com/questions/143485/implicit-operator-using-interfaces). Basically it is forbidden as per the C# language specification. – dimitar.d Mar 21 '21 at 11:06
  • Wow can't believe this is my first time hitting this wall after almost a decade of programming in C#. But it gave me the rare opportunity to close-vote my own question :D – Good Night Nerd Pride Mar 21 '21 at 11:16

0 Answers0