Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

371
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!