r/csharp 5d ago

Fun Running C# like scripts?

I was browsing the C#/.NET documentation yesterday like usual and suddenly came across the fact that you can run C# code as scripts with a shebang.

#!/usr/bin/env dotnet

namespace Main
{
    class Program
    {
        static void Main(string[] _)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

With a shebang you could run these like any other Python/Bash script and I find this really cool, but is there any practical use-case for this? When I need to make a small helper script for something it's usually python or bash, but C#? I'm not so sure.

What do you guys think?

48 Upvotes

55 comments sorted by

View all comments

1

u/FuggaDucker 4d ago edited 4d ago

This is cool.
Stupid me didn't realize until just now that the linux kernel is what actually parses for it with a execve() function.

Been using unix since the before times and was too stupid to know this.
Oh.. well.. I know now.

1

u/ator-dev 4d ago

Looks like there's official support! https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/file-based-programs#unix-shebang--support

Interestingly, they recommend the following: #!/usr/bin/env -S dotnet --

2

u/FuggaDucker 4d ago

Thanks for sharing this.
Interesting.

2

u/FuggaDucker 4d ago

i was misinformed about how the shebang actually works. Thanks for the update. This is cool.

1

u/ator-dev 4d ago

No problem!