Sunday, August 20, 2023

dotnet script: run c# from CLI

when running simple single-file c# programs with dotnet run,
it is still required to create .csproj file, and it creates "bin" and "obj" folders with many files.

Alternative is to run "c# scripts", by using a CLI tool.

The adjustment / limitation is that standard class Program with static Main should not be used in that case, just regular functions.

 dotnet-script/dotnet-script: Run C# scripts from the .NET CLI.

Run C# scripts from the .NET CLI, define NuGet packages inline and edit/debug them in VS Code - all of that with full language services support from OmniSharp.

dotnet tool install -g dotnet-script
dotnet tool list -g
# can run even from Docker container, no installation!
docker run -it dotnet-script --version

Our typical helloworld.csx might look like this:

Console.WriteLine("Hello world!");

That is all it takes and we can execute the script.
Args are accessible via the global Args 
array.dotnet script helloworld.csx

even available for embedding to applications

Dotnet CLI tool allowing you to run C# (CSX) scripts.