~/blog|
Published on

C# Scripting using dotnet-script

Authors

C# is an extremely powerful language but for small, simple tasks it tends to be a bit overkill because of the boilerplate required. dotnet-script is a project that aims to alleviate that friction. It allows C# code to be run as a single script file. No Main method, no .csproj, and transparent compilation.

Let's create a simple "Hello World" script as well as a more complex script that uses a NuGet package.

Installation

To install dotnet-script, we use the dotnet cli to install it globally:

dotnet tool install -g dotnet-script
# Optionally include specific version
dotnet tool install -g dotnet-script --version 0.53.0

The latest version will be listed at nuget.org if you wish to use a specific one.

Create Script

dotnet-script comes with an init command to generate a simple script. Let's create a directory and run that.

mkdir dotnet-script-test
cd dotnet-script-test
dotnet script init

The init script will generate 2 files: main.csx and omnisharp.json

  • omnisharp.json contains script settings like target framework and allowing nuget references
  • main.csx is scaffolded to contain a simple, functioning Hello World example

The contents of our main.csx will be:

#!/usr/bin/env dotnet-script

Console.WriteLine("Hello world!");

First, test that your script is functioning by running ./main.csx on your command line. You should see the Hello World! output. Windows machines may need to run the script using dotnet script main.csx since the "shebang" line may not be included.

Use NuGet Package

From here, we can make something a bit more complex. Let's pull in a nuget package and use it.

In a dotnet script file, nuget packages are pulled in using the #r directive. In this example, we'll pull in the Bogus nuget package in order to generate some realistic first and last names. If we browse nuget.org to find the Bogus package, the latest version is 29.0.2 at the time of writing. Below is how we pull in the package and add a using statement to make use of it.

#!/usr/bin/env dotnet-script

#r "nuget: Bogus, 29.0.2"

using Bogus;

From here, let's create a simple Person class with FirstName and LastName properties.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Let's create a person with a random name and output them using the following code:

var peopleGenerator = new Faker<Person>()
    .RuleFor(o => o.FirstName, f => f.Name.FirstName())
    .RuleFor(o => o.LastName, f => f.Name.LastName());

var person = peopleGenerator.Generate();
Console.WriteLine($"Hello, {person.FirstName} {person.LastName}");

Run this with ./main.csx on the command line. You should see something similar to this output.

./main.csx
Hello, Darian Bartell

Overall, I think using dotnet-script is an easy way to have small, concise C# scripts without the overhead of compiling them into command-line applications and having to maintain .csproj files.