Executing single file csharp files.
Have you ever wondered if .cs files can be executed without .csproj file, we can absolutely execute them with dotnet run command. This a new feature from .NET 10 (C#14)
Create a simple .cs file and save it. (eg: hello.cs)
Console.WriteLine("Hello world");Execute the file using dotnet run ./hello.cs
No imports necessary as by default this single file execution imports most used libraries.
The build files are stored in a temp folder.
This also has unix shebang (#!) support.
#!dotnet run
Console.WriteLine("Hello world");
Adjust the permissions
chmod +x hello.csExecute the program with ./hello.cs
If you also do not want the .cs extension, you can rename the filename mv hello.cs hello and it still works.
Reading command line arguments.
Add the following contents to the .cs file.
if (args.length > 0)
{
string message = string.Join(' ', args);
Console.WriteLine(message)
}You can pass the arguments as follows.
./hello -- This is a command line.The -- option indicates the all following arguments to be passed to the program.
Import nuget packages
Add this line after the unix shebang line to import the nuget package.
#:package System.CommandLine@2.0.0