Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda