-1

In my current desktop application, I evaluate dynamic C# formulas at runtime using CodeDomProvider. The formulas are written as C# snippets, and from each snippet I generate a full class and method, compile it in-memory, and invoke it with parameters.

For example, I may have a formula stored as a string like this:

var test10 = "";
if (mdDate0 != DateTime.MinValue)
    test10 = test10 + mdDate0.ToString("dd.MM.yyyy");
if (mdTextBox9 != "" && test10 != "")
    test10 = mdTextBox9 + ", (" + test10 + ")";
else
    test10 = string.Empty;
return test10;

Before executing this, I parse the formula and extract variable names (based on @VariableName), then automatically generate a C# class like this:

using System;
namespace ExpressionEngine { 
    public class InMemoryEngine { 
        public object EvaluateCode(DateTime mdDate0, string mdTextBox9) {
            var test10 = "";
            if (mdDate0 != DateTime.MinValue)
                test10 = test10 + mdDate0.ToString("dd.MM.yyyy");
            if (!string.IsNullOrEmpty(mdTextBox9) && !string.IsNullOrEmpty(test10))
                test10 = mdTextBox9 + ", (" + test10 + ")";
            else
                test10 = string.Empty;
            return test10;
        }
    } 
}

I dynamically compile and execute this using CodeDom in C#, and pass in the parameter values at runtime.

Now I’m building a React web application and want to support the same dynamic formula logic, but fully in the browser, without sending formulas to a backend server for evaluation.

Key requirements:

The formulas are already written in C# and I have many of them (over 5000).

They should be evaluated dynamically on input change events (e.g., onChange of an input field).

I want to avoid rewriting all the formulas manually in JavaScript or TypeScript.

The execution must happen entirely in the browser (no API/server call).

Question: Is it possible to execute raw or compiled C# code dynamically in the browser, from a React app?

Are there tools like Blazor WebAssembly, Mono WASM, or something else that can help me evaluate C# methods dynamically with parameter input?

Can I somehow reuse my current formula engine (or its structure) in the browser via WebAssembly, even if it requires some adaptation?

Any guidance or examples would be greatly appreciated. I’m looking for the most practical way to execute C# logic client-side in React with minimal rewriting of existing code.

I tried researching how to run C# in the browser and came across Blazor WebAssembly and Mono WASM, but from what I understood, they are designed for building entire applications, not for dynamically compiling and running custom C# code snippets with parameters (like my formulas).

I also looked into Roslyn and CodeDOM, but those seem to work only in .NET server environments, not in the browser.

I was expecting to find a way to load and execute simple C# methods (compiled or interpreted) entirely in the browser, passing values to parameters just like I do with CodeDomProvider in my desktop app. Ideally, I hoped for some WASM-based interpreter or runtime that would allow this without rewriting everything in JavaScript.

So far, I haven't found a clear way to do this in the browser from a React app.

3
  • I don't think this is possible, and for good reasons. First, you'd have to ship the whole .net runtime to people, or your code would break if they didn't have the exact version of the runtime your code uses. Second, it's a huge security issue: nobody wants to run random code downloaded from the web. Browsers have a lot of safeguards (restrictions) on what JS and web assembly they will execute, and your approach would undermine that. Commented Jun 17 at 22:04
  • 1
    You can "compile" and execute any Expression tree. When running in an environment without a compiler, the expression tree will be interpreted instead. Commented Jun 18 at 2:02
  • I would call such code "scripts" rather than "formula". I would assume the later would be some kind of fairly simple math-style expression, like ($a * 2 > 10) || $b. Commented Jun 18 at 9:29

1 Answer 1

1

Short Answer: Yes, but the solution is experimental at best and shouldn't be used in production grade software

Long Answer:

\> Note: This is just an idea nothing of this is really tested and verified to work it puts a couple of experimental C# features together to try and solve your problem. If you try it out be sure to let me know how it worked out for you ;)

As you already mentioned, C# has a feature called NativeAOT that lets you compile your code into native webAssembly see dotnet-wasi-sdk that helps you create a .wasm file from your code and A more easy to understand guide on how to obtain the .wasm file

Before being able to create your .wasm file you need to change your C# code a bit.

Use UnmanagedCallersOnlyAttribute to make your methods accessible through native code which comes with it's own set of restrictions like only being able to have static methods etc (see documentation for details)
You should be able to "hack" your way around a lot of problems you may encounter by just using the right attributes on the methods.

Change your .csproj to be able to bundle everythig into .wasm.
Should come out to something like this:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
    <InvariantGlobalization>true</InvariantGlobalization>
    <SelfContained>true</SelfContained>
    <PublishAot>true</PublishAot>
    <StripSymbols>true</StripSymbols>
    <RunAOTCompilation>true</RunAOTCompilation>
    <WasmSingleFileBundle>true</WasmSingleFileBundle>
  </PropertyGroup>
</Project>

Then releasing it using a command that should look something like this:
dotnet publish -c Release -r browser-wasm --self-contained /p:RunAOTCompilation=true
Notice the RunAOTCompilation=true to not have any dlls in your output folder.

Your compiled code should be under: bin/Release/net8.0/browser-wasm/AppBundle/ and not include any .dlls if you configured the project and executed the commands correctly.

Take the .wasm file(s) and the dotnet.js file and copy them into your react project.

And since I'm not much of a react guy I asked ChatGPT to entertain this idea and give me a react snippet to illustrate how you could use your C# methods in React so here you go.

Consider the following C# code:

using System;
using System.Runtime.InteropServices;

internal class Program
{
    [UnmanagedCallersOnly(EntryPoint = "add")]
    public static int Add(int a, int b) => a + b;
}

You could then use it in React like so:

async function loadWasmAndCall() {
  const { loadRuntime } = await import("./dotnet.js");
  const { instance } = await loadRuntime("app.wasm");

  const result = instance.exports.add(3, 5); // exported C# method
  console.log("Result from WASM:", result);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.