Home > database >  System.InvalidCastException: 'Unable to cast object of type 'Concat2Iterator`1[System.Obje
System.InvalidCastException: 'Unable to cast object of type 'Concat2Iterator`1[System.Obje

Time:01-23

If I have this line of code in Visual Studio:

object[] c = new[] { new object() }.Concat(new[] { new object() });

I get compiler error CS0266:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'object[]'. An explicit conversion exists (are you missing a cast?)

Then I use the quick actions light bulb and select "Add explicit cast", it converts my code to this, adding (object[]):

object[] c = (object[])new[] { new object() }.Concat(new[] { new object() }); 

No more compiler error; but when I run the code, it throws a System.InvalidCastException:

'Unable to cast object of type 'Concat2Iterator`1[System.Object]' to type 'System.Object[]'.'

Why would VS suggest this fix if it cannot actually make the cast at runtime? VS is giving bad advice, basically, which could lead to unexpected bugs escaping. The code compiles, and could blow up unexpectedly because you trusted VS' suggested fix.

CodePudding user response:

Concat is a LINQ method. If you look at the signature, you see it returns an IEnumerable. LINQ uses deferred execution. You will have to enumerate the results, or call ToArray or ToList to convert to a collection.

If you only want to concat arrays though, you should have a look at How do I concatenate two arrays in C#?.

  • Related