C# and .NET Core scripting with the "dotnet-script" global tool
You likely know that open source .NET Core is cross platform and it's super easy to do "Hello World" and start writing some code.
You just install .NET Core, then "dotnet new console" which will generate a project file and basic app, then "dotnet run" will compile and run your app? The 'new' command will create all the supporting code, obj, and bin folders, etc. When you do "dotnet run" it actually is a combination of "dotnet build" and "dotnet exec whatever.dll."
What could be easier?
What about .NET Core as scripting?
Check out dotnet script:
C:\Users\scott\Desktop\scriptie> dotnet tool install -g dotnet-script
You can invoke the tool using the following command: dotnet-script
C:\Users\scott\Desktop\scriptie>copy con helloworld.csx
1 file(s) copied.
C:\Users\scott\Desktop\scriptie>dotnet script helloworld.csx
NOTE: I was a little tricky there in step two. I did a "copy con filename" to copy from the console to the destination file, then used Ctrl-Z to finish the copy. Feel free to just use notepad or vim. That's not dotnet-script-specific, that's Hanselman-specific.
Pretty cool eh? If you were doing this in Linux or OSX you'll need to include a "shebang" as the first line of the script. This is a standard thing for scripting files like bash, python, etc.
This lets the operating system know what scripting engine handles this file.
If you you want to refer to a NuGet package within a script (*.csx) file, you'll use the Roslyn #r syntax:
#r "nuget: AutoMapper, 6.1.0"
Even better! Once you have "dotnet-script" installed as a global tool as above:
dotnet tool install -g dotnet-script
You can use it as a REPL! Finally, the C# REPL (Read Evaluate Print Loop) I've been asking for for only a decade! ;)
> var x = "scott hanselman";
This is super useful for a learning tool if you're teaching C# in a lab/workshop situation. Of course you could also learn using http://try.dot.net in the browser as well.
In the past you may have used ScriptCS for C# scripting. There's a number of cool C#/F# scripting options. This is certainly not a new thing:
- Mono scripting
- ScriptCS (Filip was core on this)
- Roslyn Scripting APIs (Roslyn is underneath most scripting environments)
In this case, I was very impressed with the easy of dotnet-script as a global tool and it's simplicity. Go check out https://github.com/filipw/dotnet-script and try it out today!
Sponsor: Check out the latest JetBrains Rider with built-in spell checking, enhanced debugger, Docker support, full C# 7.3 support, publishing to IIS and more advanced Unity support.