Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

372
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda