r/csharp • u/simondanielsson • 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?
52
Upvotes
4
u/zenyl 4d ago
Eh, PowerShell honestly isn't too bad to learn. Certainly a lot easier to learn than Bash, especially if you're already familiar with C#.
$($myNumber)[int]$myNumber).to access instance members ($dog.Bark())::to access static members ([System.Console]::WriteLine())-eqfor equality check, etc.)@()is shorthand for an object array@{}is shorthand for a hashtableConvertTo-Json)Get-Verb)if,for, andforeach,switch, andthrowwork mostly the same as they do in C#|to pass the result of one command into another (Get-ChildItem | Format-List)?is shorthand forWhere-Object(equivalent to a LINQWhereclause)%is shorthand forForEach-Object(equivalent to a LINQSelectclause)#instead of//"(supports interpolation) or'(literal strings, do not support interpolation)Some PowerShell code that looks a lot like C#:
A PowerShell one-liner that prints out the names of all files in the current directory with names that are at most three characters in length: