Visual C# Compiler (csc) unable to compile programs with latest language features

Viewed 32

For learning purposes, I use csc.exe myprogram.cs shipped with Visual Studio Community (my version 17.3.4) to compile basic C# programs. It mostly works, except when using what appears to be latest language features, for example, array range shorthand array[0..] or element from end shothand array[^1].

For example, when trying to access [^1] element.

Arrays.cs(58,47): error CS0518: Predefined type 'System.Index' is not defined or imported
Arrays.cs(58,47): error CS0656: Missing compiler required member 'System.Index..ctor'

I tried passing -langversion:preview to csc but still not working. Also I was unable to find proper usings for it to work.

Can I somehow get those features to work with basic csc compilation? They worked when I created csproj file and used dotnet build, but doing so was multiple times slower than using just csc. Thanks!

1 Answers

Arrays.cs(58,47): error CS0518: Predefined type 'System.Index' is not defined or imported Arrays.cs(58,47): error CS0656: Missing compiler required member 'System.Index..ctor'

The compiler uses several types to lower index / range expressions to IL. One of those types is System.Index. This error is the compiler noting that it cannot find that type which is necessary to lower that expression to IL.

This feature was added as a part of netcoreapp3.1 where csc defaults to compiling for .NET Framework applications. These types are not present in the standard set of references you get for .NET Framework hence this is why you get the error.

They worked when I created csproj file and used dotnet build ...

That worked because your project file contained something like the following:

<TargetFramework>net6.0</TargetFramework>

This targeted your application for .NET Core, the build command passed along the standard references for that and those included the System.Index type.

... but doing so was multiple times slower than using just csc.

Building a .NET application involves more than just compiling code. It is finding the correct set of references, building dependencies, compiling and deploying the resulting binaries. It's more work hence it's going to take longer to complete. Multiple times slower is not expected, particularly for repeated executions, but it will take more time that invoking csc, or any ofeth other tools used in build, directly.

Related