Apr 16, 2023

Using docker to play around with new C# features

Leia este post em português

Lire cet post en français.

In this post I presented sharplab.io, a fantastic tool that allows one to compile/run/reason about C# code, including using versions of the language that are under development but, even being a great resource it still has some limitations:

  1. In run mode, it has some restrictions on what can be executed or not (understandable, due to security concerns, resource utilization, etc)
  2. Being a website means you need an internet connection to use it (I know, I am being picky on this one).
  3. One have very little control over compiler options (like C# language version).
  4. No option to debug the code

So today I want to show you another tool in your toolbox to achieve a similar result: using Docker to experiment with new C# features without installing .NET preview versions locally or resorting to online compilers.

This post assumes you have at least basic experience with Docker (it don't require knowledge of any fancy feature though). Basically all you need to do is:

  1. Install Docker
  2. Pull latest nightly images from Microsoft repository:
    docker pull mcr.microsoft.com/dotnet/nightly/sdk:latest
  3. Run the container:
    docker run -it mcr.microsoft.com/dotnet/nightly/sdk /bin/bash

and you are done!  Once you run the command above you'll be in a terminal on a Doker container with the latest .NET build (as the time of this writing, .NET 8 Preview 4). 

Now you can experiment with new APIs, new features and what not. 

Of course you can always make your life easier. For instance, at the time of this writing, the downloaded image do not includes any reasonable text editor installed (sorry, vi fans, I am not that geek) and trying to install nano fails with a message stating that there's no candidate package for that application. Fixing it is pretty straightforward, requering just running apt update and  apt install nano but since I am lazy, my next logical step was to create a Dockerfile based on latest nightly images from MS adding the above commands:

And now you can build a custom image:

docker build . -t dotnet-latest 

docker run -it dotnet-latest

One important information you should be aware of if you are new to Docker is that container contents do not persist across sessions; this means that if you create/change any file in a session its contents will be lost when that session ends unless you take actions to persist them (unfortunately explaining how to do that is beyond the goals of this post but according to chatgpt, that is pretty straight forward - I've just entered the query "how to persist state across multiple docker sessions").

Have fun!

No comments: