Microsoft’s Linux-friendly approach to C# scripting is planned for .NET 10

Microsoft’s Linux-friendly approach to C# scripting is planned for .NET 10

Microsoft has developed a new simplified way of running C# from the command line, designed both for scripting and learning, implemented via “ignored directives” to be added to the language in the forthcoming .NET 10.

At the company’s Build event in Seattle last week, principal architect Damian Edwards demonstrated “No projects just C#” as a way to run a C# code file simply by typing:

dotnet run hello.cs

at the command line; or on Linux, using the familiar:

./hello.cs

The new approach depends on new ignored pre-processing directives to be added to C# 10, a forthcoming long-term support release expected towards the end of this year. The proposal, which was first drafted in 2020, is for directives that are ignored by the language but which have other meanings. The hashbang, valid only at the start of a file, tells the Linux operating system how to execute the code, for example:

#!/usr/bin/dotnet run

Another variant is:

#: package [package name]

which is for importing a package to be used by the code.

C# scripting introduced at Microsoft Build

Edwards described the feature as “a new way of running C#” and said at Build that it would be ideal for learners as it “gets rid of all the stuff that isn’t C#,” as well as being useful for scripting. He added that a similar approach is already available in other programming languages such as Python, Go and Rust, and that “we were lagging behind, but catching up in .NET 10.”

The .NET architect demonstrated a working web application as well as Hello World. He said that performance was poor in the current .NET 10 preview 4, the first public implementation, but that this should improve in later previews. 

Is the feature really new though? C# has had a scripting mode for more 10 years, and already supports running .csx files via the “dotnet script” command. There is also a third-party C# scripting solution called CS-Script.

Despite this previous work though, there is enthusiasm for this in the community. “This comes up on C# sub reddit all the time. People come from python or wherever and are confused when they can’t just write a single .cs file and run it. Big gap being plugged,” said one developer.

C# is well used in the Microsoft community but the company still has work to do convincing those outside that .NET and C# are worth their attention. Making .NET more accessible, especially on Linux and Mac, is likely to be worthwhile.