I have been writing some c-sharp scripts recently using the dotnet-script project. Small .csx files are great for experimenting with new concepts using C#. There is no project file, so I had a folder of scripts that could all be run interactively and independently. See the project page for the basics on installing and running csx files. In this post I wanted to document some of the tips and tricks that help when working with c-sharp scripts.
With scripts I find myself writing to the console more. I saved a bit of typing by adding the using static directive with System.Console
. This tip isn’t specific to csx, but I find myself using it more in this context:
using static System.Console; WriteLine("Hello"); WriteLine("World");
The next evolution of my scripts came when I started noticing a pattern where I would write some code and immediately print the result. Dotnet script has the -i
flag that will seed its REPL with a script file. If you omit the semicolon from the last line of the script, the line will be printed as though it were run in the REPL. I used this functionality to avoid WriteLine()
entirely.
var result = 5 + 5;
result
dotnet script -i myscript.csx 10
When a script started to outgrow console logging (but still hadn’t graduated to it’s own project), I added some unit tests with NUnit. I found that I could write and run test cases entirely self contained within a csx file like this:
#r "nuget: NUnit, 3.12.0" #r "nuget: NUnitLite, 3.12.0" using NUnit.Framework; using NUnitLite; public class MyTests { [Test] public void PassingTest() => Assert.IsTrue(true); [Test] public void FailingTest() => Assert.IsTrue(false); } new AutoRun().Execute(Args.ToArray());
2020-06-15