Home

Collection expressions confusion

I'm trying out C# 12 with LINQPad 8.0.10 (x64), and the compiled output is confusing me.

VS2022 is telling me to replace every call to Array.Empty with the new collection expression sytnax:

T[] emptyArray = Array.Empty<T>();
// becomes:
T[] emptyArray = [];

However, LINQPad's "C# 1" output, and the ILSpy output, shows that compiling to:

T[] emptyArray = new T[0];

which would obviously be sub-optimal.

This is regardless of the selected .NET version, and the state of the optimizations flag.

However, using SharpLab to examine the same code shows it correctly compiling to:

T[] emptyArray = Array.Empty<T>();

If I compile a test project in VS2022 with the same code, and then decompile it, I also see it calling Array.Empty.

Is there an obvious cause and/or fix for this confusion?

Comments

Sign In or Register to comment.