Running C# snippets in a browser

For another I’m working on I needed a way to run small C# snippets in a web browser, and since I can’t afford fancy compiler severs I turned to WASM to do the job.

I knew about Roslyn (the compiler for C#), and knew of the existence of NuGet packages that should allow for runtime compilation and execution of C# code. So I started with trying to get custom C# code to run on the web.

WASM, and Blazor, seemed like the oblivious choice but I didn’t want to have to write the entire project in Blazor, ideally I wanted this to be suited as an npm package. So I began stripping the Blazor WASM example project to see how much I could get rid of, and as it turns out you can remove almost everything. The only thing (aside from standard C# boilerplate) that was necessary for Blazor to run on the web was for binding the C# WASM and the JavaScript that initialized it together.

With that out of the way I began looking for way to communicate between JavaScript and C#. And it was easy enough, all I had to do in C# was create a static method with a special attribute and I was good to go. The JavaScript for calling that method was a bit ugly, but that’s nothing I couldn’t hide later.

So the next step was to import that Roslyn package, use it’s built in snippet executioner (and/or REPL functionality), and all would be done. Except it wasn’t that easy, because nothing ever is. The built in functions for running snippets of code relied on having a filesystem where they could find the .dlls to compile against, something we can’t have on the web. Eventually after lots of searching through the internet I found another, although more complicated, way of doing it. This new way allowed me to download and keep the .dlls in memory until they were needed.

From here on it was mostly smooth sailing, I made a TypeScript wrapper around the clumsy JavaScript interface. Added some extra features, such as a JavaScript event when the WASM had finished loading. And finished of with a small example site, and online C# REPL, it’s super simple but it shows pretty good what this package can do.

If you’re interested in any of this take a look at: the example at åsberg.net/browser-csharp, the npm package at npmjs.com/package/browser-csharp, or the source on GitHub.com/89netraM/browser-csharp.